Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(personhog): add lifecycle fencing to the leader (#78258)

José Sequeira508909d76199
diff --git a/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2.py b/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2.py
index 74aa94c20cc6..7d387f217cde 100644
--- a/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2.py
+++ b/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2.py
@@ -20,7 +20,7 @@ from ....personhog.types.v1 import (
)
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
- b"\n\"personhog/service/v1/service.proto\x12\x14personhog.service.v1\x1a\x1fpersonhog/types/v1/person.proto\x1a\x1epersonhog/types/v1/group.proto\x1a\x1fpersonhog/types/v1/cohort.proto\x1a%personhog/types/v1/feature_flag.proto2\x8b(\n\x10PersonHogService\x12X\n\tGetPerson\x12$.personhog.types.v1.GetPersonRequest\x1a%.personhog.types.v1.GetPersonResponse\x12X\n\nGetPersons\x12%.personhog.types.v1.GetPersonsRequest\x1a#.personhog.types.v1.PersonsResponse\x12d\n\x0fGetPersonByUuid\x12*.personhog.types.v1.GetPersonByUuidRequest\x1a%.personhog.types.v1.GetPersonResponse\x12f\n\x11GetPersonsByUuids\x12,.personhog.types.v1.GetPersonsByUuidsRequest\x1a#.personhog.types.v1.PersonsResponse\x12p\n\x15GetPersonByDistinctId\x120.personhog.types.v1.GetPersonByDistinctIdRequest\x1a%.personhog.types.v1.GetPersonResponse\x12\x91\x01\n\x1dGetPersonsByDistinctIdsInTeam\x128.personhog.types.v1.GetPersonsByDistinctIdsInTeamRequest\x1a6.personhog.types.v1.PersonsByDistinctIdsInTeamResponse\x12\x7f\n\x17GetPersonsByDistinctIds\x122.personhog.types.v1.GetPersonsByDistinctIdsRequest\x1a0.personhog.types.v1.PersonsByDistinctIdsResponse\x12\x82\x01\n\x17GetDistinctIdsForPerson\x122.personhog.types.v1.GetDistinctIdsForPersonRequest\x1a3.personhog.types.v1.GetDistinctIdsForPersonResponse\x12\x85\x01\n\x18GetDistinctIdsForPersons\x123.personhog.types.v1.GetDistinctIdsForPersonsRequest\x1a4.personhog.types.v1.GetDistinctIdsForPersonsResponse\x12\x88\x01\n\x19GetHashKeyOverrideContext\x124.personhog.types.v1.GetHashKeyOverrideContextRequest\x1a5.personhog.types.v1.GetHashKeyOverrideContextResponse\x12\x7f\n\x16UpsertHashKeyOverrides\x121.personhog.types.v1.UpsertHashKeyOverridesRequest\x1a2.personhog.types.v1.UpsertHashKeyOverridesResponse\x12\x94\x01\n\x1dDeleteHashKeyOverridesByTeams\x128.personhog.types.v1.DeleteHashKeyOverridesByTeamsRequest\x1a9.personhog.types.v1.DeleteHashKeyOverridesByTeamsResponse\x12w\n\x15CheckCohortMembership\x120.personhog.types.v1.CheckCohortMembershipRequest\x1a,.personhog.types.v1.CohortMembershipResponse\x12s\n\x12CountCohortMembers\x12-.personhog.types.v1.CountCohortMembersRequest\x1a..personhog.types.v1.CountCohortMembersResponse\x12s\n\x12DeleteCohortMember\x12-.personhog.types.v1.DeleteCohortMemberRequest\x1a..personhog.types.v1.DeleteCohortMemberResponse\x12\x82\x01\n\x17DeleteCohortMembersBulk\x122.personhog.types.v1.DeleteCohortMembersBulkRequest\x1a3.personhog.types.v1.DeleteCohortMembersBulkResponse\x12v\n\x13InsertCohortMembers\x12..personhog.types.v1.InsertCohortMembersRequest\x1a/.personhog.types.v1.InsertCohortMembersResponse\x12v\n\x13ListCohortMemberIds\x12..personhog.types.v1.ListCohortMemberIdsRequest\x1a/.personhog.types.v1.ListCohortMemberIdsResponse\x12U\n\x08GetGroup\x12#.personhog.types.v1.GetGroupRequest\x1a$.personhog.types.v1.GetGroupResponse\x12U\n\tGetGroups\x12$.personhog.types.v1.GetGroupsRequest\x1a\".personhog.types.v1.GroupsResponse\x12g\n\x0eGetGroupsBatch\x12).personhog.types.v1.GetGroupsBatchRequest\x1a*.personhog.types.v1.GetGroupsBatchResponse\x12[\n\nListGroups\x12%.personhog.types.v1.ListGroupsRequest\x1a&.personhog.types.v1.ListGroupsResponse\x12\x86\x01\n\x1cGetGroupTypeMappingsByTeamId\x127.personhog.types.v1.GetGroupTypeMappingsByTeamIdRequest\x1a-.personhog.types.v1.GroupTypeMappingsResponse\x12\x8d\x01\n\x1dGetGroupTypeMappingsByTeamIds\x128.personhog.types.v1.GetGroupTypeMappingsByTeamIdsRequest\x1a2.personhog.types.v1.GroupTypeMappingsBatchResponse\x12\x8c\x01\n\x1fGetGroupTypeMappingsByProjectId\x12:.personhog.types.v1.GetGroupTypeMappingsByProjectIdRequest\x1a-.personhog.types.v1.GroupTypeMappingsResponse\x12\x93\x01\n GetGroupTypeMappingsByProjectIds\x12;.personhog.types.v1.GetGroupTypeMappingsByProjectIdsRequest\x1a2.personhog.types.v1.GroupTypeMappingsBatchResponse\x12\x9d\x01\n GetGroupTypeMappingByDashboardId\x12;.personhog.types.v1.GetGroupTypeMappingByDashboardIdRequest\x1a<.personhog.types.v1.GetGroupTypeMappingByDashboardIdResponse\x12\x7f\n\x16CountGroupTypeMappings\x121.personhog.types.v1.CountGroupTypeMappingsRequest\x1a2.personhog.types.v1.CountGroupTypeMappingsResponse\x12^\n\x0bCreateGroup\x12&.personhog.types.v1.CreateGroupRequest\x1a'.personhog.types.v1.CreateGroupResponse\x12^\n\x0bUpdateGroup\x12&.personhog.types.v1.UpdateGroupRequest\x1a'.personhog.types.v1.UpdateGroupResponse\x12\x85\x01\n\x18DeleteGroupsBatchForTeam\x123.personhog.types.v1.DeleteGroupsBatchForTeamRequest\x1a4.personhog.types.v1.DeleteGroupsBatchForTeamResponse\x12\x7f\n\x16UpdateGroupTypeMapping\x121.personhog.types.v1.UpdateGroupTypeMappingRequest\x1a2.personhog.types.v1.UpdateGroupTypeMappingResponse\x12\x7f\n\x16DeleteGroupTypeMapping\x121.personhog.types.v1.DeleteGroupTypeMappingRequest\x1a2.personhog.types.v1.DeleteGroupTypeMappingResponse\x12\xa6\x01\n#DeleteGroupTypeMappingsBatchForTeam\x12>.personhog.types.v1.DeleteGroupTypeMappingsBatchForTeamRequest\x1a?.personhog.types.v1.DeleteGroupTypeMappingsBatchForTeamResponse\x12\x7f\n\x16UpdatePersonProperties\x121.personhog.types.v1.UpdatePersonPropertiesRequest\x1a2.personhog.types.v1.UpdatePersonPropertiesResponse\x12d\n\rDeletePersons\x12(.personhog.types.v1.DeletePersonsRequest\x1a).personhog.types.v1.DeletePersonsResponse\x12\x88\x01\n\x19DeletePersonsBatchForTeam\x124.personhog.types.v1.DeletePersonsBatchForTeamRequest\x1a5.personhog.types.v1.DeletePersonsBatchForTeamResponse\x12\xb2\x01\n'DeletePersonlessDistinctIdsBatchForTeam\x12B.personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamRequest\x1aC.personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamResponse\x12^\n\x0bSplitPerson\x12&.personhog.types.v1.SplitPersonRequest\x1a'.personhog.types.v1.SplitPersonResponse\x12\x9a\x01\n\x1fSetPersonDistinctIdVersionFloor\x12:.personhog.types.v1.SetPersonDistinctIdVersionFloorRequest\x1a;.personhog.types.v1.SetPersonDistinctIdVersionFloorResponse\x12|\n\x15SetPersonVersionFloor\x120.personhog.types.v1.SetPersonVersionFloorRequest\x1a1.personhog.types.v1.SetPersonVersionFloorResponseb\x06proto3"
+ b"\n\"personhog/service/v1/service.proto\x12\x14personhog.service.v1\x1a\x1fpersonhog/types/v1/person.proto\x1a\x1epersonhog/types/v1/group.proto\x1a\x1fpersonhog/types/v1/cohort.proto\x1a%personhog/types/v1/feature_flag.proto2\xce)\n\x10PersonHogService\x12X\n\tGetPerson\x12$.personhog.types.v1.GetPersonRequest\x1a%.personhog.types.v1.GetPersonResponse\x12X\n\nGetPersons\x12%.personhog.types.v1.GetPersonsRequest\x1a#.personhog.types.v1.PersonsResponse\x12d\n\x0fGetPersonByUuid\x12*.personhog.types.v1.GetPersonByUuidRequest\x1a%.personhog.types.v1.GetPersonResponse\x12f\n\x11GetPersonsByUuids\x12,.personhog.types.v1.GetPersonsByUuidsRequest\x1a#.personhog.types.v1.PersonsResponse\x12p\n\x15GetPersonByDistinctId\x120.personhog.types.v1.GetPersonByDistinctIdRequest\x1a%.personhog.types.v1.GetPersonResponse\x12\x91\x01\n\x1dGetPersonsByDistinctIdsInTeam\x128.personhog.types.v1.GetPersonsByDistinctIdsInTeamRequest\x1a6.personhog.types.v1.PersonsByDistinctIdsInTeamResponse\x12\x7f\n\x17GetPersonsByDistinctIds\x122.personhog.types.v1.GetPersonsByDistinctIdsRequest\x1a0.personhog.types.v1.PersonsByDistinctIdsResponse\x12\x82\x01\n\x17GetDistinctIdsForPerson\x122.personhog.types.v1.GetDistinctIdsForPersonRequest\x1a3.personhog.types.v1.GetDistinctIdsForPersonResponse\x12\x85\x01\n\x18GetDistinctIdsForPersons\x123.personhog.types.v1.GetDistinctIdsForPersonsRequest\x1a4.personhog.types.v1.GetDistinctIdsForPersonsResponse\x12\x88\x01\n\x19GetHashKeyOverrideContext\x124.personhog.types.v1.GetHashKeyOverrideContextRequest\x1a5.personhog.types.v1.GetHashKeyOverrideContextResponse\x12\x7f\n\x16UpsertHashKeyOverrides\x121.personhog.types.v1.UpsertHashKeyOverridesRequest\x1a2.personhog.types.v1.UpsertHashKeyOverridesResponse\x12\x94\x01\n\x1dDeleteHashKeyOverridesByTeams\x128.personhog.types.v1.DeleteHashKeyOverridesByTeamsRequest\x1a9.personhog.types.v1.DeleteHashKeyOverridesByTeamsResponse\x12w\n\x15CheckCohortMembership\x120.personhog.types.v1.CheckCohortMembershipRequest\x1a,.personhog.types.v1.CohortMembershipResponse\x12s\n\x12CountCohortMembers\x12-.personhog.types.v1.CountCohortMembersRequest\x1a..personhog.types.v1.CountCohortMembersResponse\x12s\n\x12DeleteCohortMember\x12-.personhog.types.v1.DeleteCohortMemberRequest\x1a..personhog.types.v1.DeleteCohortMemberResponse\x12\x82\x01\n\x17DeleteCohortMembersBulk\x122.personhog.types.v1.DeleteCohortMembersBulkRequest\x1a3.personhog.types.v1.DeleteCohortMembersBulkResponse\x12v\n\x13InsertCohortMembers\x12..personhog.types.v1.InsertCohortMembersRequest\x1a/.personhog.types.v1.InsertCohortMembersResponse\x12v\n\x13ListCohortMemberIds\x12..personhog.types.v1.ListCohortMemberIdsRequest\x1a/.personhog.types.v1.ListCohortMemberIdsResponse\x12U\n\x08GetGroup\x12#.personhog.types.v1.GetGroupRequest\x1a$.personhog.types.v1.GetGroupResponse\x12U\n\tGetGroups\x12$.personhog.types.v1.GetGroupsRequest\x1a\".personhog.types.v1.GroupsResponse\x12g\n\x0eGetGroupsBatch\x12).personhog.types.v1.GetGroupsBatchRequest\x1a*.personhog.types.v1.GetGroupsBatchResponse\x12[\n\nListGroups\x12%.personhog.types.v1.ListGroupsRequest\x1a&.personhog.types.v1.ListGroupsResponse\x12\x86\x01\n\x1cGetGroupTypeMappingsByTeamId\x127.personhog.types.v1.GetGroupTypeMappingsByTeamIdRequest\x1a-.personhog.types.v1.GroupTypeMappingsResponse\x12\x8d\x01\n\x1dGetGroupTypeMappingsByTeamIds\x128.personhog.types.v1.GetGroupTypeMappingsByTeamIdsRequest\x1a2.personhog.types.v1.GroupTypeMappingsBatchResponse\x12\x8c\x01\n\x1fGetGroupTypeMappingsByProjectId\x12:.personhog.types.v1.GetGroupTypeMappingsByProjectIdRequest\x1a-.personhog.types.v1.GroupTypeMappingsResponse\x12\x93\x01\n GetGroupTypeMappingsByProjectIds\x12;.personhog.types.v1.GetGroupTypeMappingsByProjectIdsRequest\x1a2.personhog.types.v1.GroupTypeMappingsBatchResponse\x12\x9d\x01\n GetGroupTypeMappingByDashboardId\x12;.personhog.types.v1.GetGroupTypeMappingByDashboardIdRequest\x1a<.personhog.types.v1.GetGroupTypeMappingByDashboardIdResponse\x12\x7f\n\x16CountGroupTypeMappings\x121.personhog.types.v1.CountGroupTypeMappingsRequest\x1a2.personhog.types.v1.CountGroupTypeMappingsResponse\x12^\n\x0bCreateGroup\x12&.personhog.types.v1.CreateGroupRequest\x1a'.personhog.types.v1.CreateGroupResponse\x12^\n\x0bUpdateGroup\x12&.personhog.types.v1.UpdateGroupRequest\x1a'.personhog.types.v1.UpdateGroupResponse\x12\x85\x01\n\x18DeleteGroupsBatchForTeam\x123.personhog.types.v1.DeleteGroupsBatchForTeamRequest\x1a4.personhog.types.v1.DeleteGroupsBatchForTeamResponse\x12\x7f\n\x16UpdateGroupTypeMapping\x121.personhog.types.v1.UpdateGroupTypeMappingRequest\x1a2.personhog.types.v1.UpdateGroupTypeMappingResponse\x12\x7f\n\x16DeleteGroupTypeMapping\x121.personhog.types.v1.DeleteGroupTypeMappingRequest\x1a2.personhog.types.v1.DeleteGroupTypeMappingResponse\x12\xa6\x01\n#DeleteGroupTypeMappingsBatchForTeam\x12>.personhog.types.v1.DeleteGroupTypeMappingsBatchForTeamRequest\x1a?.personhog.types.v1.DeleteGroupTypeMappingsBatchForTeamResponse\x12\x7f\n\x16UpdatePersonProperties\x121.personhog.types.v1.UpdatePersonPropertiesRequest\x1a2.personhog.types.v1.UpdatePersonPropertiesResponse\x12^\n\x0bFencePerson\x12&.personhog.types.v1.FencePersonRequest\x1a'.personhog.types.v1.FencePersonResponse\x12a\n\x0cReleaseFence\x12'.personhog.types.v1.ReleaseFenceRequest\x1a(.personhog.types.v1.ReleaseFenceResponse\x12d\n\rDeletePersons\x12(.personhog.types.v1.DeletePersonsRequest\x1a).personhog.types.v1.DeletePersonsResponse\x12\x88\x01\n\x19DeletePersonsBatchForTeam\x124.personhog.types.v1.DeletePersonsBatchForTeamRequest\x1a5.personhog.types.v1.DeletePersonsBatchForTeamResponse\x12\xb2\x01\n'DeletePersonlessDistinctIdsBatchForTeam\x12B.personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamRequest\x1aC.personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamResponse\x12^\n\x0bSplitPerson\x12&.personhog.types.v1.SplitPersonRequest\x1a'.personhog.types.v1.SplitPersonResponse\x12\x9a\x01\n\x1fSetPersonDistinctIdVersionFloor\x12:.personhog.types.v1.SetPersonDistinctIdVersionFloorRequest\x1a;.personhog.types.v1.SetPersonDistinctIdVersionFloorResponse\x12|\n\x15SetPersonVersionFloor\x120.personhog.types.v1.SetPersonVersionFloorRequest\x1a1.personhog.types.v1.SetPersonVersionFloorResponseb\x06proto3"
)
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
@@ -28,4 +28,4 @@ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "personhog.service.v1.servic
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals["_PERSONHOGSERVICE"]._serialized_start = 198
- _globals["_PERSONHOGSERVICE"]._serialized_end = 5329
+ _globals["_PERSONHOGSERVICE"]._serialized_end = 5524
diff --git a/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2_grpc.py b/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2_grpc.py
index edc85e0f3337..a1370fa8afc9 100644
--- a/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2_grpc.py
+++ b/posthog/personhog_client/proto/generated/personhog/service/v1/service_pb2_grpc.py
@@ -249,6 +249,18 @@ class PersonHogServiceStub:
response_deserializer=personhog_dot_types_dot_v1_dot_person__pb2.UpdatePersonPropertiesResponse.FromString,
_registered_method=True,
)
+ self.FencePerson = channel.unary_unary(
+ "/personhog.service.v1.PersonHogService/FencePerson",
+ request_serializer=personhog_dot_types_dot_v1_dot_person__pb2.FencePersonRequest.SerializeToString,
+ response_deserializer=personhog_dot_types_dot_v1_dot_person__pb2.FencePersonResponse.FromString,
+ _registered_method=True,
+ )
+ self.ReleaseFence = channel.unary_unary(
+ "/personhog.service.v1.PersonHogService/ReleaseFence",
+ request_serializer=personhog_dot_types_dot_v1_dot_person__pb2.ReleaseFenceRequest.SerializeToString,
+ response_deserializer=personhog_dot_types_dot_v1_dot_person__pb2.ReleaseFenceResponse.FromString,
+ _registered_method=True,
+ )
self.DeletePersons = channel.unary_unary(
"/personhog.service.v1.PersonHogService/DeletePersons",
request_serializer=personhog_dot_types_dot_v1_dot_person__pb2.DeletePersonsRequest.SerializeToString,
@@ -502,6 +514,21 @@ class PersonHogServiceServicer:
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
+ def FencePerson(self, request, context):
+ """Lifecycle fence RPCs (routed to leader). Internal: called only by the
+ lifecycle saga runner in personhog-identity — see leader.proto for
+ semantics.
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details("Method not implemented!")
+ raise NotImplementedError("Method not implemented!")
+
+ def ReleaseFence(self, request, context):
+ """Missing associated documentation comment in .proto file."""
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details("Method not implemented!")
+ raise NotImplementedError("Method not implemented!")
+
def DeletePersons(self, request, context):
"""Person deletes
WARNING: This is a write operation on person data. It should route to the leader
@@ -724,6 +751,16 @@ def add_PersonHogServiceServicer_to_server(servicer, server):
request_deserializer=personhog_dot_types_dot_v1_dot_person__pb2.UpdatePersonPropertiesRequest.FromString,
response_serializer=personhog_dot_types_dot_v1_dot_person__pb2.UpdatePersonPropertiesResponse.SerializeToString,
),
+ "FencePerson": grpc.unary_unary_rpc_method_handler(
+ servicer.FencePerson,
+ request_deserializer=personhog_dot_types_dot_v1_dot_person__pb2.FencePersonRequest.FromString,
+ response_serializer=personhog_dot_types_dot_v1_dot_person__pb2.FencePersonResponse.SerializeToString,
+ ),
+ "ReleaseFence": grpc.unary_unary_rpc_method_handler(
+ servicer.ReleaseFence,
+ request_deserializer=personhog_dot_types_dot_v1_dot_person__pb2.ReleaseFenceRequest.FromString,
+ response_serializer=personhog_dot_types_dot_v1_dot_person__pb2.ReleaseFenceResponse.SerializeToString,
+ ),
"DeletePersons": grpc.unary_unary_rpc_method_handler(
servicer.DeletePersons,
request_deserializer=personhog_dot_types_dot_v1_dot_person__pb2.DeletePersonsRequest.FromString,
@@ -1815,6 +1852,66 @@ class PersonHogService:
_registered_method=True,
)
+ @staticmethod
+ def FencePerson(
+ request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None,
+ ):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ "/personhog.service.v1.PersonHogService/FencePerson",
+ personhog_dot_types_dot_v1_dot_person__pb2.FencePersonRequest.SerializeToString,
+ personhog_dot_types_dot_v1_dot_person__pb2.FencePersonResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True,
+ )
+
+ @staticmethod
+ def ReleaseFence(
+ request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None,
+ ):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ "/personhog.service.v1.PersonHogService/ReleaseFence",
+ personhog_dot_types_dot_v1_dot_person__pb2.ReleaseFenceRequest.SerializeToString,
+ personhog_dot_types_dot_v1_dot_person__pb2.ReleaseFenceResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True,
+ )
+
@staticmethod
def DeletePersons(
request,
diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.py b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.py
index 660a84068472..c87faf3cd876 100644
--- a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.py
+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.py
@@ -15,80 +15,92 @@ _sym_db = _symbol_database.Default()
from ....personhog.types.v1 import common_pb2 as personhog_dot_types_dot_v1_dot_common__pb2
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
- b'\n\x1fpersonhog/types/v1/person.proto\x12\x12personhog.types.v1\x1a\x1fpersonhog/types/v1/common.proto"\x9e\x02\n\x06Person\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x12\x0f\n\x07team_id\x18\x03 \x01(\x03\x12\x12\n\nproperties\x18\x04 \x01(\x0c\x12"\n\x1aproperties_last_updated_at\x18\x05 \x01(\x0c\x12!\n\x19properties_last_operation\x18\x06 \x01(\x0c\x12\x12\n\ncreated_at\x18\x07 \x01(\x03\x12\x0f\n\x07version\x18\x08 \x01(\x03\x12\x15\n\ris_identified\x18\t \x01(\x08\x12\x17\n\nis_user_id\x18\n \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x0b \x01(\x03H\x01\x88\x01\x01B\r\n\x0b_is_user_idB\x0f\n\r_last_seen_at"N\n\x15DistinctIdWithVersion\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x14\n\x07version\x18\x02 \x01(\x03H\x00\x88\x01\x01B\n\n\x08_version"h\n\x15PersonWithDistinctIds\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"g\n\x11PersonDistinctIds\x12\x11\n\tperson_id\x18\x01 \x01(\x03\x12?\n\x0cdistinct_ids\x18\x02 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\x87\x01\n\x18PersonWithTeamDistinctId\x12/\n\x03key\x18\x01 \x01(\x0b2".personhog.types.v1.TeamDistinctId\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"m\n\x10GetPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"O\n\x11GetPersonResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"o\n\x11GetPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"S\n\x0fPersonsResponse\x12+\n\x07persons\x18\x01 \x03(\x0b2\x1a.personhog.types.v1.Person\x12\x13\n\x0bmissing_ids\x18\x02 \x03(\x03"n\n\x16GetPersonByUuidRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"q\n\x18GetPersonsByUuidsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\r\n\x05uuids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"{\n\x1cGetPersonByDistinctIdRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"\x84\x01\n$GetPersonsByDistinctIdsInTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cdistinct_ids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"`\n"PersonsByDistinctIdsInTeamResponse\x12:\n\x07results\x18\x01 \x03(\x0b2).personhog.types.v1.PersonWithDistinctIds"\x96\x01\n\x1eGetPersonsByDistinctIdsRequest\x12=\n\x11team_distinct_ids\x18\x01 \x03(\x0b2".personhog.types.v1.TeamDistinctId\x125\n\x0cread_options\x18\x02 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"]\n\x1cPersonsByDistinctIdsResponse\x12=\n\x07results\x18\x01 \x03(\x0b2,.personhog.types.v1.PersonWithTeamDistinctId"\x99\x01\n\x1eGetDistinctIdsForPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x12\n\x05limit\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x08\n\x06_limit"b\n\x1fGetDistinctIdsForPersonResponse\x12?\n\x0cdistinct_ids\x18\x01 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\xb1\x01\n\x1fGetDistinctIdsForPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x1d\n\x10limit_per_person\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x13\n\x11_limit_per_person"f\n GetDistinctIdsForPersonsResponse\x12B\n\x13person_distinct_ids\x18\x01 \x03(\x0b2%.personhog.types.v1.PersonDistinctIds"\x80\x02\n\x1dUpdatePersonPropertiesRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x12\n\nevent_name\x18\x03 \x01(\t\x12\x16\n\x0eset_properties\x18\x04 \x01(\x0c\x12\x1b\n\x13set_once_properties\x18\x05 \x01(\x0c\x12\x18\n\x10unset_properties\x18\x06 \x03(\t\x12\x1a\n\ris_identified\x18\x07 \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x08 \x01(\x03H\x01\x88\x01\x01B\x10\n\x0e_is_identifiedB\x0f\n\r_last_seen_at"m\n\x1eUpdatePersonPropertiesResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01\x12\x0f\n\x07updated\x18\x02 \x01(\x08B\t\n\x07_person"=\n\x14DeletePersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cperson_uuids\x18\x02 \x03(\t".\n\x15DeletePersonsResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"G\n DeletePersonsBatchForTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nbatch_size\x18\x02 \x01(\x03":\n!DeletePersonsBatchForTeamResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"U\n.DeletePersonlessDistinctIdsBatchForTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nbatch_size\x18\x02 \x01(\x03"H\n/DeletePersonlessDistinctIdsBatchForTeamResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"W\n\x12SplitPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x1d\n\x15distinct_ids_to_split\x18\x03 \x03(\t"\x8e\x01\n\x0bSplitResult\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x17\n\x0fnew_person_uuid\x18\x02 \x01(\t\x12\x1a\n\x12new_person_version\x18\x03 \x01(\x03\x12\x13\n\x0bpdi_version\x18\x04 \x01(\x03\x12 \n\x18new_person_created_at_ms\x18\x05 \x01(\x03"F\n\x13SplitPersonResponse\x12/\n\x06splits\x18\x01 \x03(\x0b2\x1f.personhog.types.v1.SplitResult"c\n&SetPersonDistinctIdVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"e\n\'SetPersonDistinctIdVersionFloorResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"W\n\x1cSetPersonVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"0\n\x1dSetPersonVersionFloorResponse\x12\x0f\n\x07updated\x18\x01 \x01(\x08b\x06proto3'
+ b'\n\x1fpersonhog/types/v1/person.proto\x12\x12personhog.types.v1\x1a\x1fpersonhog/types/v1/common.proto"\xb2\x02\n\x06Person\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x12\x0f\n\x07team_id\x18\x03 \x01(\x03\x12\x12\n\nproperties\x18\x04 \x01(\x0c\x12"\n\x1aproperties_last_updated_at\x18\x05 \x01(\x0c\x12!\n\x19properties_last_operation\x18\x06 \x01(\x0c\x12\x12\n\ncreated_at\x18\x07 \x01(\x03\x12\x0f\n\x07version\x18\x08 \x01(\x03\x12\x15\n\ris_identified\x18\t \x01(\x08\x12\x17\n\nis_user_id\x18\n \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x0b \x01(\x03H\x01\x88\x01\x01\x12\x12\n\nis_deleted\x18\x0c \x01(\x08B\r\n\x0b_is_user_idB\x0f\n\r_last_seen_at"N\n\x15DistinctIdWithVersion\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x14\n\x07version\x18\x02 \x01(\x03H\x00\x88\x01\x01B\n\n\x08_version"h\n\x15PersonWithDistinctIds\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"g\n\x11PersonDistinctIds\x12\x11\n\tperson_id\x18\x01 \x01(\x03\x12?\n\x0cdistinct_ids\x18\x02 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\x87\x01\n\x18PersonWithTeamDistinctId\x12/\n\x03key\x18\x01 \x01(\x0b2".personhog.types.v1.TeamDistinctId\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"m\n\x10GetPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"O\n\x11GetPersonResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"o\n\x11GetPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"S\n\x0fPersonsResponse\x12+\n\x07persons\x18\x01 \x03(\x0b2\x1a.personhog.types.v1.Person\x12\x13\n\x0bmissing_ids\x18\x02 \x03(\x03"n\n\x16GetPersonByUuidRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"q\n\x18GetPersonsByUuidsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\r\n\x05uuids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"{\n\x1cGetPersonByDistinctIdRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"\x84\x01\n$GetPersonsByDistinctIdsInTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cdistinct_ids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"`\n"PersonsByDistinctIdsInTeamResponse\x12:\n\x07results\x18\x01 \x03(\x0b2).personhog.types.v1.PersonWithDistinctIds"\x96\x01\n\x1eGetPersonsByDistinctIdsRequest\x12=\n\x11team_distinct_ids\x18\x01 \x03(\x0b2".personhog.types.v1.TeamDistinctId\x125\n\x0cread_options\x18\x02 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"]\n\x1cPersonsByDistinctIdsResponse\x12=\n\x07results\x18\x01 \x03(\x0b2,.personhog.types.v1.PersonWithTeamDistinctId"\x99\x01\n\x1eGetDistinctIdsForPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x12\n\x05limit\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x08\n\x06_limit"b\n\x1fGetDistinctIdsForPersonResponse\x12?\n\x0cdistinct_ids\x18\x01 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\xb1\x01\n\x1fGetDistinctIdsForPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x1d\n\x10limit_per_person\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x13\n\x11_limit_per_person"f\n GetDistinctIdsForPersonsResponse\x12B\n\x13person_distinct_ids\x18\x01 \x03(\x0b2%.personhog.types.v1.PersonDistinctIds"\x80\x02\n\x1dUpdatePersonPropertiesRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x12\n\nevent_name\x18\x03 \x01(\t\x12\x16\n\x0eset_properties\x18\x04 \x01(\x0c\x12\x1b\n\x13set_once_properties\x18\x05 \x01(\x0c\x12\x18\n\x10unset_properties\x18\x06 \x03(\t\x12\x1a\n\ris_identified\x18\x07 \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x08 \x01(\x03H\x01\x88\x01\x01B\x10\n\x0e_is_identifiedB\x0f\n\r_last_seen_at"m\n\x1eUpdatePersonPropertiesResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01\x12\x0f\n\x07updated\x18\x02 \x01(\x08B\t\n\x07_person"=\n\x14DeletePersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cperson_uuids\x18\x02 \x03(\t".\n\x15DeletePersonsResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"G\n DeletePersonsBatchForTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nbatch_size\x18\x02 \x01(\x03":\n!DeletePersonsBatchForTeamResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"U\n.DeletePersonlessDistinctIdsBatchForTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nbatch_size\x18\x02 \x01(\x03"H\n/DeletePersonlessDistinctIdsBatchForTeamResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"W\n\x12SplitPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x1d\n\x15distinct_ids_to_split\x18\x03 \x03(\t"\x8e\x01\n\x0bSplitResult\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x17\n\x0fnew_person_uuid\x18\x02 \x01(\t\x12\x1a\n\x12new_person_version\x18\x03 \x01(\x03\x12\x13\n\x0bpdi_version\x18\x04 \x01(\x03\x12 \n\x18new_person_created_at_ms\x18\x05 \x01(\x03"F\n\x13SplitPersonResponse\x12/\n\x06splits\x18\x01 \x03(\x0b2\x1f.personhog.types.v1.SplitResult"c\n&SetPersonDistinctIdVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"e\n\'SetPersonDistinctIdVersionFloorResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"W\n\x1cSetPersonVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"0\n\x1dSetPersonVersionFloorResponse\x12\x0f\n\x07updated\x18\x01 \x01(\x08"}\n\x12FencePersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\r\n\x05op_id\x18\x03 \x01(\t\x124\n\x07op_type\x18\x04 \x01(\x0e2#.personhog.types.v1.LifecycleOpType"A\n\x13FencePersonResponse\x12*\n\x06sealed\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.Person"\xd6\x01\n\x13ReleaseFenceRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x13\n\x0bperson_uuid\x18\x03 \x01(\t\x12\r\n\x05op_id\x18\x04 \x01(\t\x123\n\x07outcome\x18\x05 \x01(\x0e2".personhog.types.v1.ReleaseOutcome\x12\x1b\n\x0esealed_version\x18\x06 \x01(\x03H\x00\x88\x01\x01\x12\x12\n\ncreated_at\x18\x07 \x01(\x03B\x11\n\x0f_sealed_version"\x16\n\x14ReleaseFenceResponse*o\n\x0fLifecycleOpType\x12!\n\x1dLIFECYCLE_OP_TYPE_UNSPECIFIED\x10\x00\x12\x1c\n\x18LIFECYCLE_OP_TYPE_DELETE\x10\x01\x12\x1b\n\x17LIFECYCLE_OP_TYPE_MERGE\x10\x02*m\n\x0eReleaseOutcome\x12\x1f\n\x1bRELEASE_OUTCOME_UNSPECIFIED\x10\x00\x12\x1d\n\x19RELEASE_OUTCOME_COMMITTED\x10\x01\x12\x1b\n\x17RELEASE_OUTCOME_ABORTED\x10\x02b\x06proto3'
)
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "personhog.types.v1.person_pb2", _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
+ _globals["_LIFECYCLEOPTYPE"]._serialized_start = 4448
+ _globals["_LIFECYCLEOPTYPE"]._serialized_end = 4559
+ _globals["_RELEASEOUTCOME"]._serialized_start = 4561
+ _globals["_RELEASEOUTCOME"]._serialized_end = 4670
_globals["_PERSON"]._serialized_start = 89
- _globals["_PERSON"]._serialized_end = 375
- _globals["_DISTINCTIDWITHVERSION"]._serialized_start = 377
- _globals["_DISTINCTIDWITHVERSION"]._serialized_end = 455
- _globals["_PERSONWITHDISTINCTIDS"]._serialized_start = 457
- _globals["_PERSONWITHDISTINCTIDS"]._serialized_end = 561
- _globals["_PERSONDISTINCTIDS"]._serialized_start = 563
- _globals["_PERSONDISTINCTIDS"]._serialized_end = 666
- _globals["_PERSONWITHTEAMDISTINCTID"]._serialized_start = 669
- _globals["_PERSONWITHTEAMDISTINCTID"]._serialized_end = 804
- _globals["_GETPERSONREQUEST"]._serialized_start = 806
- _globals["_GETPERSONREQUEST"]._serialized_end = 915
- _globals["_GETPERSONRESPONSE"]._serialized_start = 917
- _globals["_GETPERSONRESPONSE"]._serialized_end = 996
- _globals["_GETPERSONSREQUEST"]._serialized_start = 998
- _globals["_GETPERSONSREQUEST"]._serialized_end = 1109
- _globals["_PERSONSRESPONSE"]._serialized_start = 1111
- _globals["_PERSONSRESPONSE"]._serialized_end = 1194
- _globals["_GETPERSONBYUUIDREQUEST"]._serialized_start = 1196
- _globals["_GETPERSONBYUUIDREQUEST"]._serialized_end = 1306
- _globals["_GETPERSONSBYUUIDSREQUEST"]._serialized_start = 1308
- _globals["_GETPERSONSBYUUIDSREQUEST"]._serialized_end = 1421
- _globals["_GETPERSONBYDISTINCTIDREQUEST"]._serialized_start = 1423
- _globals["_GETPERSONBYDISTINCTIDREQUEST"]._serialized_end = 1546
- _globals["_GETPERSONSBYDISTINCTIDSINTEAMREQUEST"]._serialized_start = 1549
- _globals["_GETPERSONSBYDISTINCTIDSINTEAMREQUEST"]._serialized_end = 1681
- _globals["_PERSONSBYDISTINCTIDSINTEAMRESPONSE"]._serialized_start = 1683
- _globals["_PERSONSBYDISTINCTIDSINTEAMRESPONSE"]._serialized_end = 1779
- _globals["_GETPERSONSBYDISTINCTIDSREQUEST"]._serialized_start = 1782
- _globals["_GETPERSONSBYDISTINCTIDSREQUEST"]._serialized_end = 1932
- _globals["_PERSONSBYDISTINCTIDSRESPONSE"]._serialized_start = 1934
- _globals["_PERSONSBYDISTINCTIDSRESPONSE"]._serialized_end = 2027
- _globals["_GETDISTINCTIDSFORPERSONREQUEST"]._serialized_start = 2030
- _globals["_GETDISTINCTIDSFORPERSONREQUEST"]._serialized_end = 2183
- _globals["_GETDISTINCTIDSFORPERSONRESPONSE"]._serialized_start = 2185
- _globals["_GETDISTINCTIDSFORPERSONRESPONSE"]._serialized_end = 2283
- _globals["_GETDISTINCTIDSFORPERSONSREQUEST"]._serialized_start = 2286
- _globals["_GETDISTINCTIDSFORPERSONSREQUEST"]._serialized_end = 2463
- _globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_start = 2465
- _globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_end = 2567
- _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_start = 2570
- _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_end = 2826
- _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_start = 2828
- _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_end = 2937
- _globals["_DELETEPERSONSREQUEST"]._serialized_start = 2939
- _globals["_DELETEPERSONSREQUEST"]._serialized_end = 3000
- _globals["_DELETEPERSONSRESPONSE"]._serialized_start = 3002
- _globals["_DELETEPERSONSRESPONSE"]._serialized_end = 3048
- _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_start = 3050
- _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_end = 3121
- _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_start = 3123
- _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_end = 3181
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_start = 3183
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_end = 3268
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_start = 3270
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_end = 3342
- _globals["_SPLITPERSONREQUEST"]._serialized_start = 3344
- _globals["_SPLITPERSONREQUEST"]._serialized_end = 3431
- _globals["_SPLITRESULT"]._serialized_start = 3434
- _globals["_SPLITRESULT"]._serialized_end = 3576
- _globals["_SPLITPERSONRESPONSE"]._serialized_start = 3578
- _globals["_SPLITPERSONRESPONSE"]._serialized_end = 3648
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_start = 3650
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_end = 3749
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_start = 3751
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_end = 3852
- _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_start = 3854
- _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_end = 3941
- _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_start = 3943
- _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_end = 3991
+ _globals["_PERSON"]._serialized_end = 395
+ _globals["_DISTINCTIDWITHVERSION"]._serialized_start = 397
+ _globals["_DISTINCTIDWITHVERSION"]._serialized_end = 475
+ _globals["_PERSONWITHDISTINCTIDS"]._serialized_start = 477
+ _globals["_PERSONWITHDISTINCTIDS"]._serialized_end = 581
+ _globals["_PERSONDISTINCTIDS"]._serialized_start = 583
+ _globals["_PERSONDISTINCTIDS"]._serialized_end = 686
+ _globals["_PERSONWITHTEAMDISTINCTID"]._serialized_start = 689
+ _globals["_PERSONWITHTEAMDISTINCTID"]._serialized_end = 824
+ _globals["_GETPERSONREQUEST"]._serialized_start = 826
+ _globals["_GETPERSONREQUEST"]._serialized_end = 935
+ _globals["_GETPERSONRESPONSE"]._serialized_start = 937
+ _globals["_GETPERSONRESPONSE"]._serialized_end = 1016
+ _globals["_GETPERSONSREQUEST"]._serialized_start = 1018
+ _globals["_GETPERSONSREQUEST"]._serialized_end = 1129
+ _globals["_PERSONSRESPONSE"]._serialized_start = 1131
+ _globals["_PERSONSRESPONSE"]._serialized_end = 1214
+ _globals["_GETPERSONBYUUIDREQUEST"]._serialized_start = 1216
+ _globals["_GETPERSONBYUUIDREQUEST"]._serialized_end = 1326
+ _globals["_GETPERSONSBYUUIDSREQUEST"]._serialized_start = 1328
+ _globals["_GETPERSONSBYUUIDSREQUEST"]._serialized_end = 1441
+ _globals["_GETPERSONBYDISTINCTIDREQUEST"]._serialized_start = 1443
+ _globals["_GETPERSONBYDISTINCTIDREQUEST"]._serialized_end = 1566
+ _globals["_GETPERSONSBYDISTINCTIDSINTEAMREQUEST"]._serialized_start = 1569
+ _globals["_GETPERSONSBYDISTINCTIDSINTEAMREQUEST"]._serialized_end = 1701
+ _globals["_PERSONSBYDISTINCTIDSINTEAMRESPONSE"]._serialized_start = 1703
+ _globals["_PERSONSBYDISTINCTIDSINTEAMRESPONSE"]._serialized_end = 1799
+ _globals["_GETPERSONSBYDISTINCTIDSREQUEST"]._serialized_start = 1802
+ _globals["_GETPERSONSBYDISTINCTIDSREQUEST"]._serialized_end = 1952
+ _globals["_PERSONSBYDISTINCTIDSRESPONSE"]._serialized_start = 1954
+ _globals["_PERSONSBYDISTINCTIDSRESPONSE"]._serialized_end = 2047
+ _globals["_GETDISTINCTIDSFORPERSONREQUEST"]._serialized_start = 2050
+ _globals["_GETDISTINCTIDSFORPERSONREQUEST"]._serialized_end = 2203
+ _globals["_GETDISTINCTIDSFORPERSONRESPONSE"]._serialized_start = 2205
+ _globals["_GETDISTINCTIDSFORPERSONRESPONSE"]._serialized_end = 2303
+ _globals["_GETDISTINCTIDSFORPERSONSREQUEST"]._serialized_start = 2306
+ _globals["_GETDISTINCTIDSFORPERSONSREQUEST"]._serialized_end = 2483
+ _globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_start = 2485
+ _globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_end = 2587
+ _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_start = 2590
+ _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_end = 2846
+ _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_start = 2848
+ _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_end = 2957
+ _globals["_DELETEPERSONSREQUEST"]._serialized_start = 2959
+ _globals["_DELETEPERSONSREQUEST"]._serialized_end = 3020
+ _globals["_DELETEPERSONSRESPONSE"]._serialized_start = 3022
+ _globals["_DELETEPERSONSRESPONSE"]._serialized_end = 3068
+ _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_start = 3070
+ _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_end = 3141
+ _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_start = 3143
+ _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_end = 3201
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_start = 3203
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_end = 3288
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_start = 3290
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_end = 3362
+ _globals["_SPLITPERSONREQUEST"]._serialized_start = 3364
+ _globals["_SPLITPERSONREQUEST"]._serialized_end = 3451
+ _globals["_SPLITRESULT"]._serialized_start = 3454
+ _globals["_SPLITRESULT"]._serialized_end = 3596
+ _globals["_SPLITPERSONRESPONSE"]._serialized_start = 3598
+ _globals["_SPLITPERSONRESPONSE"]._serialized_end = 3668
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_start = 3670
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_end = 3769
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_start = 3771
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_end = 3872
+ _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_start = 3874
+ _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_end = 3961
+ _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_start = 3963
+ _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_end = 4011
+ _globals["_FENCEPERSONREQUEST"]._serialized_start = 4013
+ _globals["_FENCEPERSONREQUEST"]._serialized_end = 4138
+ _globals["_FENCEPERSONRESPONSE"]._serialized_start = 4140
+ _globals["_FENCEPERSONRESPONSE"]._serialized_end = 4205
+ _globals["_RELEASEFENCEREQUEST"]._serialized_start = 4208
+ _globals["_RELEASEFENCEREQUEST"]._serialized_end = 4422
+ _globals["_RELEASEFENCERESPONSE"]._serialized_start = 4424
+ _globals["_RELEASEFENCERESPONSE"]._serialized_end = 4446
diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi
index 80a41648fd9d..4f38318f6df6 100644
--- a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi
+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi
@@ -12,11 +12,33 @@ from google.protobuf import (
descriptor as _descriptor,
message as _message,
)
-from google.protobuf.internal import containers as _containers
+from google.protobuf.internal import (
+ containers as _containers,
+ enum_type_wrapper as _enum_type_wrapper,
+)
from personhog.types.v1 import common_pb2 as _common_pb2
DESCRIPTOR: _descriptor.FileDescriptor
+class LifecycleOpType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
+ __slots__ = ()
+ LIFECYCLE_OP_TYPE_UNSPECIFIED: _ClassVar[LifecycleOpType]
+ LIFECYCLE_OP_TYPE_DELETE: _ClassVar[LifecycleOpType]
+ LIFECYCLE_OP_TYPE_MERGE: _ClassVar[LifecycleOpType]
+
+class ReleaseOutcome(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
+ __slots__ = ()
+ RELEASE_OUTCOME_UNSPECIFIED: _ClassVar[ReleaseOutcome]
+ RELEASE_OUTCOME_COMMITTED: _ClassVar[ReleaseOutcome]
+ RELEASE_OUTCOME_ABORTED: _ClassVar[ReleaseOutcome]
+
+LIFECYCLE_OP_TYPE_UNSPECIFIED: LifecycleOpType
+LIFECYCLE_OP_TYPE_DELETE: LifecycleOpType
+LIFECYCLE_OP_TYPE_MERGE: LifecycleOpType
+RELEASE_OUTCOME_UNSPECIFIED: ReleaseOutcome
+RELEASE_OUTCOME_COMMITTED: ReleaseOutcome
+RELEASE_OUTCOME_ABORTED: ReleaseOutcome
+
class Person(_message.Message):
__slots__ = (
"id",
@@ -30,6 +52,7 @@ class Person(_message.Message):
"is_identified",
"is_user_id",
"last_seen_at",
+ "is_deleted",
)
ID_FIELD_NUMBER: _ClassVar[int]
UUID_FIELD_NUMBER: _ClassVar[int]
@@ -42,6 +65,7 @@ class Person(_message.Message):
IS_IDENTIFIED_FIELD_NUMBER: _ClassVar[int]
IS_USER_ID_FIELD_NUMBER: _ClassVar[int]
LAST_SEEN_AT_FIELD_NUMBER: _ClassVar[int]
+ IS_DELETED_FIELD_NUMBER: _ClassVar[int]
id: int
uuid: str
team_id: int
@@ -53,6 +77,7 @@ class Person(_message.Message):
is_identified: bool
is_user_id: bool
last_seen_at: int
+ is_deleted: bool
def __init__(
self,
@@ -67,6 +92,7 @@ class Person(_message.Message):
is_identified: bool = ...,
is_user_id: bool = ...,
last_seen_at: _Optional[int] = ...,
+ is_deleted: bool = ...,
) -> None: ...
class DistinctIdWithVersion(_message.Message):
@@ -493,3 +519,62 @@ class SetPersonVersionFloorResponse(_message.Message):
updated: bool
def __init__(self, updated: bool = ...) -> None: ...
+
+class FencePersonRequest(_message.Message):
+ __slots__ = ("team_id", "person_id", "op_id", "op_type")
+ TEAM_ID_FIELD_NUMBER: _ClassVar[int]
+ PERSON_ID_FIELD_NUMBER: _ClassVar[int]
+ OP_ID_FIELD_NUMBER: _ClassVar[int]
+ OP_TYPE_FIELD_NUMBER: _ClassVar[int]
+ team_id: int
+ person_id: int
+ op_id: str
+ op_type: LifecycleOpType
+
+ def __init__(
+ self,
+ team_id: _Optional[int] = ...,
+ person_id: _Optional[int] = ...,
+ op_id: _Optional[str] = ...,
+ op_type: _Optional[_Union[LifecycleOpType, str]] = ...,
+ ) -> None: ...
+
+class FencePersonResponse(_message.Message):
+ __slots__ = ("sealed",)
+ SEALED_FIELD_NUMBER: _ClassVar[int]
+ sealed: Person
+
+ def __init__(self, sealed: _Optional[_Union[Person, _Mapping]] = ...) -> None: ...
+
+class ReleaseFenceRequest(_message.Message):
+ __slots__ = ("team_id", "person_id", "person_uuid", "op_id", "outcome", "sealed_version", "created_at")
+ TEAM_ID_FIELD_NUMBER: _ClassVar[int]
+ PERSON_ID_FIELD_NUMBER: _ClassVar[int]
+ PERSON_UUID_FIELD_NUMBER: _ClassVar[int]
+ OP_ID_FIELD_NUMBER: _ClassVar[int]
+ OUTCOME_FIELD_NUMBER: _ClassVar[int]
+ SEALED_VERSION_FIELD_NUMBER: _ClassVar[int]
+ CREATED_AT_FIELD_NUMBER: _ClassVar[int]
+ team_id: int
+ person_id: int
+ person_uuid: str
+ op_id: str
+ outcome: ReleaseOutcome
+ sealed_version: int
+ created_at: int
+
+ def __init__(
+ self,
+ team_id: _Optional[int] = ...,
+ person_id: _Optional[int] = ...,
+ person_uuid: _Optional[str] = ...,
+ op_id: _Optional[str] = ...,
+ outcome: _Optional[_Union[ReleaseOutcome, str]] = ...,
+ sealed_version: _Optional[int] = ...,
+ created_at: _Optional[int] = ...,
+ ) -> None: ...
+
+class ReleaseFenceResponse(_message.Message):
+ __slots__ = ()
+
+ def __init__(self) -> None: ...
diff --git a/proto/personhog/leader/v1/leader.proto b/proto/personhog/leader/v1/leader.proto
index 19ff78e2cf41..d6a4adf91a05 100644
--- a/proto/personhog/leader/v1/leader.proto
+++ b/proto/personhog/leader/v1/leader.proto
@@ -16,4 +16,37 @@ service PersonHogLeader {
// Strong consistency read: returns the latest person state from the leader's cache.
rpc GetPerson(personhog.types.v1.GetPersonRequest) returns (personhog.types.v1.GetPersonResponse);
+
+ // Internal, saga-runner only. Freeze a person for a lifecycle operation:
+ // under the per-person lock, record the fence in the leader's in-memory
+ // fence map and seal the newest cached state, returning it in the same
+ // response — no gap for a write to sneak into. The fence's durable
+ // record is NOT this map: it is the saga's mark row, committed before
+ // this RPC is ever called; a leader taking partition ownership rebuilds
+ // its map from the live marks before accepting writes. Fencing produces
+ // nothing to the changelog and does not advance the version — the
+ // sealed version is the person's current one. While fenced, writes fail
+ // FAILED_PRECONDITION with an `x-person-fenced` metadata key carrying
+ // the op type; reads are unaffected. Re-fencing with the same op_id
+ // re-seals with fresh state (what makes the saga's seal step safe to
+ // repeat); a different op_id is rejected — at most one lifecycle op
+ // holds a person. The fence never lapses on a timer: only ReleaseFence
+ // (or the op being observed finished) clears it.
+ rpc FencePerson(personhog.types.v1.FencePersonRequest) returns (personhog.types.v1.FencePersonResponse);
+
+ // The closing half of FencePerson. `committed` (the person was
+ // destroyed): verify the op against its live mark row — the request
+ // alone is never sufficient to destroy a person; a release whose op
+ // holds no live mark is refused FAILED_PRECONDITION (fail closed) —
+ // then produce the death document to the changelog — is_deleted =
+ // true, version = max(sealed_version, current) + 1 (sealed + 1 per the
+ // RFC; the max is defense in depth until broker producer fencing lands)
+ // — then evict the cache entry and drop the fence. `aborted`: drop the
+ // fence, keep the entry, produce nothing; the person resumes normal
+ // life. Idempotent — the request carries everything needed to re-derive
+ // the death document, so a restarted leader produces it
+ // deterministically; duplicates are absorbed downstream by version, and
+ // a mark already settled as deleted absorbs the retry without a second
+ // record.
+ rpc ReleaseFence(personhog.types.v1.ReleaseFenceRequest) returns (personhog.types.v1.ReleaseFenceResponse);
}
diff --git a/proto/personhog/service/v1/service.proto b/proto/personhog/service/v1/service.proto
index eb641689bffd..802eeddafc60 100644
--- a/proto/personhog/service/v1/service.proto
+++ b/proto/personhog/service/v1/service.proto
@@ -64,6 +64,12 @@ service PersonHogService {
// Person property updates (routed to leader)
rpc UpdatePersonProperties(personhog.types.v1.UpdatePersonPropertiesRequest) returns (personhog.types.v1.UpdatePersonPropertiesResponse);
+ // Lifecycle fence RPCs (routed to leader). Internal: called only by the
+ // lifecycle saga runner in personhog-identity — see leader.proto for
+ // semantics.
+ rpc FencePerson(personhog.types.v1.FencePersonRequest) returns (personhog.types.v1.FencePersonResponse);
+ rpc ReleaseFence(personhog.types.v1.ReleaseFenceRequest) returns (personhog.types.v1.ReleaseFenceResponse);
+
// Person deletes
// WARNING: This is a write operation on person data. It should route to the leader
// once personhog-leader supports deletes. Currently routed through the replica
diff --git a/proto/personhog/types/v1/person.proto b/proto/personhog/types/v1/person.proto
index 6c061e9df6cc..4ac027679574 100644
--- a/proto/personhog/types/v1/person.proto
+++ b/proto/personhog/types/v1/person.proto
@@ -18,6 +18,11 @@ message Person {
optional bool is_user_id = 10;
// Epoch milliseconds (matching created_at); the writer decodes it as such.
optional int64 last_seen_at = 11;
+ // True on a death document: the changelog record the leader produces when
+ // a lifecycle saga destroys the person (version = sealed_version + 1).
+ // Consumers treat the person as gone; the writer projects it as the
+ // Postgres tombstone. proto3 default (false) keeps old records live.
+ bool is_deleted = 12;
}
// DistinctIdWithVersion pairs a distinct_id with its version for consistency tracking
@@ -281,3 +286,72 @@ message SetPersonVersionFloorResponse {
// True if a row was updated (the stored version was below min_version).
bool updated = 1;
}
+
+// FencePersonRequest freezes a person for a lifecycle operation (see
+// PersonHogLeader.FencePerson). op_id is the saga's caller-supplied UUID;
+// op_type selects the rejection surfaced to writers while the fence holds.
+message FencePersonRequest {
+ int64 team_id = 1;
+ int64 person_id = 2;
+ string op_id = 3;
+ LifecycleOpType op_type = 4;
+}
+
+// The kind of lifecycle operation — mirrors lifecycle_op.op_type. The
+// canonical string mapping lives on this enum's impl in personhog-proto;
+// derive from it everywhere instead of repeating the literals.
+enum LifecycleOpType {
+ LIFECYCLE_OP_TYPE_UNSPECIFIED = 0;
+ LIFECYCLE_OP_TYPE_DELETE = 1;
+ LIFECYCLE_OP_TYPE_MERGE = 2;
+}
+
+message FencePersonResponse {
+ // The sealed state: the person's final word — no write can follow it
+ // while the fence holds. Delete uses sealed.version only; merge seals
+ // the full document (properties included).
+ //
+ // Failure is reported through the gRPC status, never in-band:
+ // FAILED_PRECONDITION with x-person-fenced metadata when another op
+ // holds the person, NOT_FOUND when the person is destroyed,
+ // FAILED_PRECONDITION when this pod does not serve the partition (the
+ // retry re-routes), and RESOURCE_EXHAUSTED when the fence map is at
+ // capacity (retry later).
+ Person sealed = 1;
+}
+
+// ReleaseFenceRequest closes a fence (see PersonHogLeader.ReleaseFence).
+// person_uuid, sealed_version, and created_at travel in the request so a
+// leader with no cache entry — after a restart — re-derives the death
+// document deterministically. All three come from the sealed state the
+// fence returned (the saga persists it in the mark row for replay).
+message ReleaseFenceRequest {
+ int64 team_id = 1;
+ int64 person_id = 2;
+ string person_uuid = 3;
+ string op_id = 4;
+ ReleaseOutcome outcome = 5;
+ // The version sealed at fence time. The death document is produced at
+ // sealed_version + 1. Required when outcome = COMMITTED. Explicitly
+ // optional because 0 is a legitimate sealed version — a fresh person
+ // stub is created at version 0 — so absence must stay distinguishable
+ // from it.
+ optional int64 sealed_version = 6;
+ // The person's creation time as sealed at fence time, in epoch
+ // seconds — the unit Person.created_at carries end to end (the leader
+ // loads `timestamp()`, the writer binds via `epoch_secs_to_datetime`).
+ // The death document carries it verbatim — a cold leader has nothing
+ // to re-derive it from, and the writer projects it onto the tombstone
+ // row. Required when outcome = COMMITTED.
+ int64 created_at = 7;
+}
+
+enum ReleaseOutcome {
+ RELEASE_OUTCOME_UNSPECIFIED = 0;
+ // The person was destroyed: produce the death document, evict, unfence.
+ RELEASE_OUTCOME_COMMITTED = 1;
+ // The op backed out: unfence, keep the entry, produce nothing.
+ RELEASE_OUTCOME_ABORTED = 2;
+}
+
+message ReleaseFenceResponse {}
diff --git a/rust/personhog-common/src/client.rs b/rust/personhog-common/src/client.rs
index dfb966dac798..869639a3ca26 100644
--- a/rust/personhog-common/src/client.rs
+++ b/rust/personhog-common/src/client.rs
@@ -12,7 +12,8 @@ use tonic::{Request, Status};
use personhog_proto::personhog::service::v1::person_hog_service_client::PersonHogServiceClient;
use personhog_proto::personhog::types::v1::{
- ConsistencyLevel, GetPersonRequest, Person, ReadOptions, UpdatePersonPropertiesRequest,
+ ConsistencyLevel, FencePersonRequest, FencePersonResponse, GetPersonRequest, Person,
+ ReadOptions, ReleaseFenceRequest, ReleaseFenceResponse, UpdatePersonPropertiesRequest,
UpdatePersonPropertiesResponse,
};
@@ -77,6 +78,40 @@ impl RouterClient {
.map(|response| response.into_inner().person)
}
+ /// Leader-routed lifecycle fence (saga runner only): freeze the person
+ /// and return its sealed state.
+ pub async fn fence_person(
+ &self,
+ request: FencePersonRequest,
+ ) -> Result<FencePersonResponse, Status> {
+ let (team_id, person_id) = (request.team_id, request.person_id);
+ let mut request = Request::new(request);
+ request.set_timeout(self.request_timeout);
+ stamp_person_routing_headers(&mut request, team_id, person_id);
+ self.inner
+ .clone()
+ .fence_person(request)
+ .await
+ .map(|response| response.into_inner())
+ }
+
+ /// Leader-routed fence release (saga runner only): committed produces
+ /// the death document, aborted resumes the person's normal life.
+ pub async fn release_fence(
+ &self,
+ request: ReleaseFenceRequest,
+ ) -> Result<ReleaseFenceResponse, Status> {
+ let (team_id, person_id) = (request.team_id, request.person_id);
+ let mut request = Request::new(request);
+ request.set_timeout(self.request_timeout);
+ stamp_person_routing_headers(&mut request, team_id, person_id);
+ self.inner
+ .clone()
+ .release_fence(request)
+ .await
+ .map(|response| response.into_inner())
+ }
+
fn build_update_request(
&self,
request: UpdatePersonPropertiesRequest,
diff --git a/rust/personhog-common/src/persons.rs b/rust/personhog-common/src/persons.rs
index 0617f9af1704..95b7da93933e 100644
--- a/rust/personhog-common/src/persons.rs
+++ b/rust/personhog-common/src/persons.rs
@@ -58,6 +58,9 @@ impl From<Person> for personhog_proto::personhog::types::v1::Person {
is_identified: person.is_identified,
is_user_id: person.is_user_id,
last_seen_at: person.last_seen_at.map(|t| t.timestamp_millis()),
+ // Read-plane rows: the queries behind this struct filter
+ // tombstones out.
+ is_deleted: false,
}
}
}
diff --git a/rust/personhog-identity/.sqlx/query-1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0.json b/rust/personhog-identity/.sqlx/query-1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0.json
new file mode 100644
index 000000000000..92fdb4c2b71d
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0"
+}
diff --git a/rust/personhog-identity/.sqlx/query-e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8.json b/rust/personhog-identity/.sqlx/query-e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8.json
new file mode 100644
index 000000000000..68606422c1e1
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op\n SET lease_expires_at = now() + make_interval(secs => $2)\n WHERE op_id = $1 AND completed_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Float8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8"
+}
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index 30ba41995c29..1d7c8f3a9bcc 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -21,12 +21,16 @@ use serde_json::Value;
use sqlx::postgres::PgPool;
use uuid::Uuid;
+use personhog_proto::personhog::types::v1::LifecycleOpType;
+
use crate::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
STEP_COMPLETED,
};
-pub const OP_TYPE_DELETE: &str = "delete";
+// Derived from the shared enum so the op-type string cannot drift from
+// the leader's fence records or the lifecycle_op CHECK constraint.
+pub const OP_TYPE_DELETE: &str = LifecycleOpType::Delete.as_op_type_str();
/// The delete saga's non-terminal steps, in order. Stored as text in
/// `lifecycle_op.step` (the engine is generic over op types, so its API is
diff --git a/rust/personhog-leader/src/cache/partitioned.rs b/rust/personhog-leader/src/cache/partitioned.rs
index 0873e293a6fa..dda11894d505 100644
--- a/rust/personhog-leader/src/cache/partitioned.rs
+++ b/rust/personhog-leader/src/cache/partitioned.rs
@@ -124,6 +124,7 @@ mod tests {
created_at: 1700000000,
version: 1,
is_identified: false,
+ is_deleted: false,
last_seen_at: None,
approx_bytes: approx_person_bytes(64),
}
diff --git a/rust/personhog-leader/src/cache/persons.rs b/rust/personhog-leader/src/cache/persons.rs
index 3b9b2c4362d0..c2f7d1c392fd 100644
--- a/rust/personhog-leader/src/cache/persons.rs
+++ b/rust/personhog-leader/src/cache/persons.rs
@@ -36,6 +36,11 @@ pub struct CachedPerson {
pub created_at: i64,
pub version: i64,
pub is_identified: bool,
+ /// True when this entry is a recovered death document: the person was
+ /// destroyed and this version closes its stream. Kept in cache (rather
+ /// than dropped) so reads answer an authoritative not-found instead of
+ /// falling back to a PG row the writer may not have tombstoned yet.
+ pub is_deleted: bool,
/// Epoch milliseconds of the person's last observed activity, when
/// known (matching `created_at`'s unit). Max-merged on update — the
/// value only ever advances — and deliberately not a change by itself.
@@ -62,6 +67,7 @@ impl TryFrom<Person> for CachedPerson {
created_at: person.created_at,
version: person.version,
is_identified: person.is_identified,
+ is_deleted: person.is_deleted,
last_seen_at: person.last_seen_at,
approx_bytes,
})
@@ -159,6 +165,7 @@ mod tests {
created_at: 1700000000,
version: 1,
is_identified: false,
+ is_deleted: false,
last_seen_at: None,
approx_bytes: approx_person_bytes(64),
}
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index 7b8f090ce2d4..c4839432ca69 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -237,6 +237,16 @@ pub struct Config {
#[envconfig(default = "1000000")]
pub emitted_versions_max_entries: usize,
+ /// Hard cap on live lifecycle fences (~100 bytes each). The fence map
+ /// grows one entry per person frozen by a lifecycle op and has no
+ /// eviction, so this is the memory fuse against a surge of ops from a
+ /// huge customer: at the cap, new FencePerson calls shed with
+ /// RESOURCE_EXHAUSTED — backpressure the saga's retries absorb —
+ /// while re-seals of already-fenced persons and the takeover scan
+ /// (marks already live; the freeze must hold) are exempt.
+ #[envconfig(default = "250000")]
+ pub fence_map_max_entries: usize,
+
// ── PG fallback ───────────────────────────────────────────────
/// Postgres URL for cache miss fallback. If empty, cache misses
/// return NotFound without querying PG. Must point at the primary:
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index b4fd3084ef66..d36538520e6b 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -10,6 +10,7 @@ use tracing::{error, info};
use crate::cache::{DirtyIndex, PartitionedCache};
use crate::emitted::EmittedVersions;
+use crate::fence::{drop_partition_fences, rebuild_partition_fences, FenceMap};
use crate::fencing::{heal_fence, FenceGuard, FencedChangelogProducers, HealOutcome};
use crate::inflight::InflightTracker;
use crate::warming::{warm_from_kafka, WarmClientPools, WarmingConfig};
@@ -49,6 +50,14 @@ pub struct LeaderHandoffHandler {
inflight: Arc<InflightTracker>,
dirty_index: Arc<DirtyIndex>,
warming: WarmingConfig,
+ /// The in-process fence copies, rebuilt from the live marks at every
+ /// ownership boundary (see the fence module for the durability model).
+ fences: FenceMap,
+ /// Pool for the takeover scan — the cache-miss fallback pool. Without
+ /// it (dev fixtures) fences are not rebuilt on takeover and only
+ /// FencePerson calls fill the map.
+ fence_scan_pool: Option<sqlx::PgPool>,
+ num_partitions: u32,
pools: Arc<WarmClientPools>,
/// Present when broker-enforced epoch fencing is on: acquiring a
/// partition initializes its transactional producer (fencing every
@@ -82,6 +91,9 @@ impl LeaderHandoffHandler {
inflight: Arc<InflightTracker>,
dirty_index: Arc<DirtyIndex>,
warming: WarmingConfig,
+ fences: FenceMap,
+ fence_scan_pool: Option<sqlx::PgPool>,
+ num_partitions: u32,
pools: Arc<WarmClientPools>,
fenced: Option<Arc<FencedChangelogProducers>>,
authority: Option<Arc<AuthorityClock>>,
@@ -92,6 +104,9 @@ impl LeaderHandoffHandler {
inflight,
dirty_index,
warming,
+ fences,
+ fence_scan_pool,
+ num_partitions,
pools,
fenced,
authority,
@@ -219,6 +234,29 @@ impl HandoffHandler for LeaderHandoffHandler {
}
async fn warm_partition(&self, partition: u32) -> Result<()> {
+ // The takeover scan: rebuild the partition's lifecycle fences from
+ // the live marks BEFORE warming — the partition becomes servable
+ // the moment `warm_from_kafka` installs it in the cache, and a
+ // fenced person must never be writable in that gap. A mark
+ // committed after this read arrives as a FencePerson call to this
+ // (now current) owner, so the two sources cover every mark; a
+ // fence installed for a partition that is not yet serving is
+ // harmless.
+ if let Some(pool) = &self.fence_scan_pool {
+ let installed =
+ rebuild_partition_fences(pool, &self.fences, partition, self.num_partitions)
+ .await
+ .map_err(|e| personhog_coordination::error::Error::HandoffFailed {
+ partition,
+ reason: format!("fence takeover scan failed: {e}"),
+ })?;
+ if installed > 0 {
+ info!(
+ partition,
+ installed, "rebuilt lifecycle fences from live marks"
+ );
+ }
+ }
info!(partition, "warming partition cache from kafka");
self.check_authority(partition, "warm")?;
// Broker-side fencing before the warm read, not after: acquiring
@@ -311,6 +349,9 @@ impl HandoffHandler for LeaderHandoffHandler {
// The new owner's warming rebuilds its own marks; stale marks here
// would only pin memory for a partition this pod no longer serves.
self.dirty_index.clear_partition(partition);
+ // Same for the lifecycle fences: the new owner's takeover scan
+ // rebuilds its own.
+ drop_partition_fences(&self.fences, partition, self.num_partitions);
// The incoming owner derives versions from the changelog, which
// is the authority these floors stood in for; carrying them would
// only constrain a partition this pod no longer serves.
@@ -416,6 +457,9 @@ mod tests {
max_backoff: Duration::from_secs(5),
},
},
+ Arc::new(dashmap::DashMap::new()),
+ None,
+ 4,
pools,
None,
None,
diff --git a/rust/personhog-leader/src/fence.rs b/rust/personhog-leader/src/fence.rs
new file mode 100644
index 000000000000..d2a79e9f5816
--- /dev/null
+++ b/rust/personhog-leader/src/fence.rs
@@ -0,0 +1,323 @@
+//! Lifecycle fence state: which persons are frozen by a live lifecycle
+//! operation, and how a leader rebuilds that knowledge across ownership
+//! changes.
+//!
+//! The fence's source of truth is not this map — it is the saga's mark row
+//! (`lifecycle_op_person` in `marked`/`sealed`), committed on the persons
+//! primary before `FencePerson` is ever called. The map is the leader's
+//! in-process copy, and on the write path it is authoritative: a fenced
+//! write is rejected from memory alone, never a database read.
+//!
+//! Postgres is read in exactly one place — the takeover scan, once per
+//! partition acquisition, before the partition accepts writes. That plus
+//! the `FencePerson` RPC are the only two ways an entry gets in, and
+//! together they cover every mark. Entries leave in exactly two ways: a
+//! `ReleaseFence`, or dropping the whole partition.
+//!
+//! The leader never reclaims a fence on its own, and deliberately so.
+//! personhog-identity owns lifecycle correctness: every op is driven to a
+//! terminal state (lease steal, sweeper resumption), so a `ReleaseFence`
+//! always eventually arrives. An entry that outlives a crashed saga is
+//! not stale — the mark is still live, the op really is unfinished, and
+//! the person really should stay frozen. For that guarantee to hold, a
+//! release must never *vacuously* succeed: both fence RPCs verify this
+//! pod serves the partition, so a misrouted call fails and identity's
+//! retry reaches the pod whose map actually gates the writes.
+//!
+//! The map is NOT a cache: it has no capacity limit and no eviction path
+//! — losing an entry while continuing to serve would violate consistency,
+//! not degrade it.
+//!
+//! One known window: a takeover that runs between a release being acked
+//! and the saga settling its mark row installs a fence for an op that is
+//! already done — a ghost no `ReleaseFence` will ever clear. The
+//! [`FenceHealer`] closes it lazily: a write rejected by a fence triggers
+//! a non-blocking mark-row read, and a fence whose op has settled is
+//! dropped, so the next write goes through instead of waiting for the
+//! partition to change hands.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use dashmap::DashMap;
+use metrics::{counter, gauge, histogram};
+use sqlx::postgres::PgPool;
+use sqlx::Row;
+use tonic::Status;
+use uuid::Uuid;
+
+use personhog_common::partitioning::partition_for_person;
+use personhog_proto::personhog::types::v1::LifecycleOpType;
+
+use crate::cache::PersonCacheKey;
+
+/// A person's live fence: the operation that froze it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct FenceState {
+ pub op_id: Uuid,
+ pub op_type: LifecycleOpType,
+}
+
+pub type FenceMap = Arc<DashMap<PersonCacheKey, FenceState>>;
+
+/// Metadata key carried on fenced-write rejections: `delete` or `merge`.
+/// Callers distinguish "this person is being destroyed, back off" from
+/// ordinary precondition failures by this key's presence.
+pub const FENCED_METADATA_KEY: &str = "x-person-fenced";
+/// Metadata key carrying the fencing operation's id on rejections.
+pub const FENCED_OP_ID_METADATA_KEY: &str = "x-person-fenced-op-id";
+
+/// The typed rejection for a write to a fenced person: PERSON_DELETING /
+/// PERSON_MERGING per the RFC, encoded as FAILED_PRECONDITION plus
+/// metadata (gRPC has no custom codes).
+pub fn fenced_status(state: &FenceState) -> Status {
+ let what = match state.op_type {
+ LifecycleOpType::Delete => "PERSON_DELETING",
+ LifecycleOpType::Merge => "PERSON_MERGING",
+ LifecycleOpType::Unspecified => "PERSON_FENCED",
+ };
+ let label = state.op_type.as_op_type_str();
+ let mut status = Status::failed_precondition(format!(
+ "{what}: person is fenced by lifecycle op {}",
+ state.op_id
+ ));
+ if let Ok(value) = label.parse() {
+ status.metadata_mut().insert(FENCED_METADATA_KEY, value);
+ }
+ if let Ok(value) = state.op_id.to_string().parse() {
+ status
+ .metadata_mut()
+ .insert(FENCED_OP_ID_METADATA_KEY, value);
+ }
+ status
+}
+
+/// How long the takeover scan may run before the handoff gives up. The
+/// scan gates a partition's return to service, and it reads a set whose
+/// size depends on another service's liveness (marks stay live while
+/// their op does), so it is bounded here rather than trusted to be
+/// small. Expiry fails the handoff — a partition whose fences cannot be
+/// known must not serve writes.
+const SCAN_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// The takeover scan: load every live mark belonging to `partition` and
+/// install it in the fence map, before the partition accepts writes.
+///
+/// The scan cannot target a partition (the partition is a murmur2 hash
+/// Postgres cannot compute), so it reads the whole live-mark set — the
+/// partial mark index contains nothing but live marks — and filters
+/// in-process with the same partition function request validation uses.
+/// The join to `lifecycle_op` for the op type costs a lookup per row, so
+/// this is not an index-only read; it stays cheap because the live-mark
+/// set is small while ops complete. Merge targets are claimed but never
+/// fenced, so they are excluded.
+///
+/// The partition's existing entries are dropped first, so a re-warm
+/// (a handoff cancelled after warming, then re-acquired) converges
+/// instead of accumulating. Returns how many fences were installed.
+pub async fn rebuild_partition_fences(
+ pool: &PgPool,
+ fences: &FenceMap,
+ partition: u32,
+ num_partitions: u32,
+) -> Result<usize, sqlx::Error> {
+ let start = std::time::Instant::now();
+ let query = sqlx::query(
+ r#"
+ SELECT lop.team_id, lop.person_id, lop.op_id, o.op_type
+ FROM lifecycle_op_person lop
+ JOIN lifecycle_op o ON o.op_id = lop.op_id
+ WHERE lop.status IN ('marked', 'sealed')
+ AND lop.role <> 'target'
+ "#,
+ )
+ .fetch_all(pool);
+
+ let rows = match tokio::time::timeout(SCAN_TIMEOUT, query).await {
+ Ok(result) => result?,
+ Err(_) => {
+ counter!("personhog_leader_fence_scan_timeouts_total").increment(1);
+ return Err(sqlx::Error::PoolTimedOut);
+ }
+ };
+ histogram!("personhog_leader_fence_scan_duration_seconds")
+ .record(start.elapsed().as_secs_f64());
+ // Read next to installed is the scan's amplification: it reads the
+ // whole live-mark set (the partition is a hash Postgres cannot
+ // compute) and keeps ~1/num_partitions of it. This ratio growing is
+ // the signal that the scan-the-world design needs revisiting.
+ counter!("personhog_leader_fence_scan_rows_read_total").increment(rows.len() as u64);
+
+ // Converge rather than accumulate: this partition's fences are
+ // exactly what the marks say, not that plus whatever a previous warm
+ // left behind.
+ drop_partition_fences(fences, partition, num_partitions);
+
+ let mut installed = 0usize;
+ for row in rows {
+ let team_id: i32 = row.get("team_id");
+ let person_id: i64 = row.get("person_id");
+ if partition_for_person(team_id as i64, person_id, num_partitions) != partition {
+ continue;
+ }
+ let op_id: Uuid = row.get("op_id");
+ let op_type: String = row.get("op_type");
+ fences.insert(
+ PersonCacheKey {
+ team_id: team_id as i64,
+ person_id,
+ },
+ FenceState {
+ op_id,
+ op_type: LifecycleOpType::from_op_type_str(&op_type),
+ },
+ );
+ installed += 1;
+ }
+ counter!("personhog_leader_fence_scan_fences_installed_total").increment(installed as u64);
+ gauge!("personhog_leader_fences_active").set(fences.len() as f64);
+ Ok(installed)
+}
+
+/// Drop every fence belonging to `partition` — the counterpart of
+/// [`rebuild_partition_fences`] for partition release. The new owner
+/// rebuilds its own; stale entries here would only pin memory for persons
+/// this pod no longer serves (misrouted requests are already rejected by
+/// partition validation).
+pub fn drop_partition_fences(fences: &FenceMap, partition: u32, num_partitions: u32) -> usize {
+ let before = fences.len();
+ fences.retain(|key, _| {
+ partition_for_person(key.team_id, key.person_id, num_partitions) != partition
+ });
+ gauge!("personhog_leader_fences_active").set(fences.len() as f64);
+ before - fences.len()
+}
+
+/// How long a person's heal verdict stands before a rejected write may
+/// trigger another mark-row read. Bounds the PG read rate for a person
+/// that is legitimately fenced and still receiving writes: at most one
+/// point read per person per cooldown, however hot the write storm.
+const HEAL_COOLDOWN: Duration = Duration::from_secs(5);
+
+/// Above this many tracked persons, expired cooldown stamps are pruned on
+/// the next trigger. Keeps the tracker bounded without a sweeper task.
+const HEAL_TRACKER_PRUNE_THRESHOLD: usize = 10_000;
+
+/// Lazily removes ghost fences — entries whose op has already settled its
+/// mark row, so no `ReleaseFence` will ever arrive for them (see the
+/// module docs for how the takeover scan creates these).
+///
+/// Triggered from the write path when a fence rejects a write, but never
+/// on it: the check runs on a spawned task, the write fails as fenced
+/// either way, and the caller's retry finds the fence gone. Fail-closed
+/// by construction — the fence is only dropped when Postgres, the source
+/// of truth, says the mark is no longer live, and only if the entry still
+/// belongs to the op that was checked (a newer op's fence is never
+/// touched).
+pub struct FenceHealer {
+ pool: PgPool,
+ fences: FenceMap,
+ /// Per-person stamp of the last triggered check, for the cooldown.
+ last_checked: DashMap<PersonCacheKey, std::time::Instant>,
+}
+
+impl FenceHealer {
+ pub fn new(pool: PgPool, fences: FenceMap) -> Self {
+ Self {
+ pool,
+ fences,
+ last_checked: DashMap::new(),
+ }
+ }
+
+ /// Kick off a background ghost check for `key`, unless one ran within
+ /// the cooldown. Called after a write was rejected by `state`.
+ pub fn maybe_heal(self: &Arc<Self>, key: PersonCacheKey, state: FenceState) {
+ let now = std::time::Instant::now();
+ if self.last_checked.len() > HEAL_TRACKER_PRUNE_THRESHOLD {
+ self.last_checked
+ .retain(|_, stamp| now.duration_since(*stamp) < HEAL_COOLDOWN);
+ }
+ // The entry API keeps check-and-stamp atomic: one write storm
+ // triggers one check per cooldown, not one per rejection.
+ match self.last_checked.entry(key.clone()) {
+ dashmap::mapref::entry::Entry::Occupied(mut entry)
+ if now.duration_since(*entry.get()) >= HEAL_COOLDOWN =>
+ {
+ entry.insert(now);
+ }
+ dashmap::mapref::entry::Entry::Vacant(entry) => {
+ entry.insert(now);
+ }
+ dashmap::mapref::entry::Entry::Occupied(_) => return,
+ }
+ let healer = Arc::clone(self);
+ tokio::spawn(async move {
+ healer.check_and_heal(key, state).await;
+ });
+ }
+
+ async fn check_and_heal(&self, key: PersonCacheKey, state: FenceState) {
+ let status = match mark_status(&self.pool, state.op_id, key.team_id, key.person_id).await {
+ Ok(status) => status,
+ Err(e) => {
+ counter!("personhog_leader_fence_heals_total", "outcome" => "error").increment(1);
+ tracing::warn!(
+ team_id = key.team_id,
+ person_id = key.person_id,
+ op_id = %state.op_id,
+ error = %e,
+ "ghost-fence check failed; fence kept"
+ );
+ return;
+ }
+ };
+ // Live is what the takeover scan installs from; anything else —
+ // a terminal status or no row at all — means the op has settled
+ // and its release already happened somewhere.
+ if matches!(status.as_deref(), Some("marked") | Some("sealed")) {
+ counter!("personhog_leader_fence_heals_total", "outcome" => "still_live").increment(1);
+ return;
+ }
+ // Conditional on the op id: a fence re-installed by a newer op in
+ // the meantime is someone else's and stays.
+ let removed = self
+ .fences
+ .remove_if(&key, |_, current| current.op_id == state.op_id)
+ .is_some();
+ if removed {
+ self.last_checked.remove(&key);
+ gauge!("personhog_leader_fences_active").set(self.fences.len() as f64);
+ counter!("personhog_leader_fence_heals_total", "outcome" => "removed").increment(1);
+ tracing::info!(
+ team_id = key.team_id,
+ person_id = key.person_id,
+ op_id = %state.op_id,
+ "removed a ghost fence: its op has already settled"
+ );
+ }
+ }
+}
+
+/// The committed-release check: the status of the op's mark row for this
+/// person, straight from the source of truth. `None` when the op never
+/// claimed the person (or claimed it only as a merge target — targets are
+/// never destroyed). A committed release must find a live mark here before
+/// it may produce a death document: the request alone must never be enough
+/// to destroy a person.
+pub async fn mark_status(
+ pool: &PgPool,
+ op_id: Uuid,
+ team_id: i64,
+ person_id: i64,
+) -> Result<Option<String>, sqlx::Error> {
+ sqlx::query_scalar(
+ "SELECT status FROM lifecycle_op_person \
+ WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role <> 'target'",
+ )
+ .bind(op_id)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .fetch_optional(pool)
+ .await
+}
diff --git a/rust/personhog-leader/src/lib.rs b/rust/personhog-leader/src/lib.rs
index 59c43ae4c77d..b912d3153810 100644
--- a/rust/personhog-leader/src/lib.rs
+++ b/rust/personhog-leader/src/lib.rs
@@ -2,6 +2,7 @@ pub mod cache;
pub mod config;
pub mod coordination;
pub mod emitted;
+pub mod fence;
pub mod fencing;
pub mod inflight;
pub mod kafka;
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 1f898dcd83da..81976b962664 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -293,6 +293,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!(num_partitions, "loaded partition count from etcd");
let locks = Arc::new(DashMap::new());
+ let fences: personhog_leader::fence::FenceMap = Arc::new(DashMap::new());
let inflight = Arc::new(InflightTracker::new());
let dirty_index = Arc::new(DirtyIndex::new(config.dirty_index_max_entries));
// One per pod, shared by the service that raises floors and the
@@ -316,6 +317,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
kafka_producer.clone(),
config.ingestion_warnings_topic.clone(),
);
+ let fence_scan_pool = fallback.as_ref().map(|f| f.pool.clone());
let fenced = if config.kafka_transactional_fencing {
// Every one of these is derived from LEASE_TTL rather than set
// directly, so an operator debugging a fenced-write timeout has
@@ -428,10 +430,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.properties_trim_target,
),
warnings.clone(),
+ Arc::clone(&fences),
fenced.clone(),
gated_authority.clone(),
Arc::clone(&emitted_versions),
- );
+ )
+ .with_fence_capacity(config.fence_map_max_entries);
let warm_pools = Arc::new(WarmClientPools::new(
&config.kafka,
@@ -461,6 +465,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
max_backoff: Duration::from_millis(config.warm_retry_max_backoff_ms),
},
},
+ Arc::clone(&fences),
+ fence_scan_pool,
+ num_partitions,
Arc::clone(&warm_pools),
fenced.clone(),
gated_authority.clone(),
diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rs
index bbe8feb7da07..dd8e3582647f 100644
--- a/rust/personhog-leader/src/pg.rs
+++ b/rust/personhog-leader/src/pg.rs
@@ -113,6 +113,9 @@ pub async fn load_person_from_pg(
created_at: created_at.timestamp_millis(),
version: version.unwrap_or(0),
is_identified,
+ // The query filters is_deleted = false; a tombstoned row is
+ // answered as not-found above, never loaded.
+ is_deleted: false,
last_seen_at: last_seen_at.map(|t| t.timestamp_millis()),
}))
}
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index e7982cfafe31..83580f9b8df2 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -6,8 +6,9 @@ use dashmap::DashMap;
use metrics::{counter, histogram};
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeader;
use personhog_proto::personhog::types::v1::{
- GetPersonRequest, GetPersonResponse, Person, UpdatePersonPropertiesRequest,
- UpdatePersonPropertiesResponse,
+ FencePersonRequest, FencePersonResponse, GetPersonRequest, GetPersonResponse, LifecycleOpType,
+ Person, ReleaseFenceRequest, ReleaseFenceResponse, ReleaseOutcome,
+ UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
};
use rdkafka::producer::FutureProducer;
use tokio::sync::Mutex;
@@ -23,6 +24,7 @@ use crate::cache::{
PersonCacheKey,
};
use crate::emitted::{EmittedVersionGuard, EmittedVersions};
+use crate::fence::{fenced_status, mark_status, FenceHealer, FenceMap, FenceState};
use crate::fencing::{FencedChangelogProducers, FencedProduceError};
use crate::inflight::InflightTracker;
use crate::kafka::produce_person_changelog;
@@ -34,6 +36,10 @@ use personhog_common::properties::{
jsonb_column_size, sanitize_for_jsonb, trim_properties_to_fit_size, TrimResult,
};
+/// Mirrors the config's `fence_map_max_entries` default; production
+/// overrides via [`PersonHogLeaderService::with_fence_capacity`].
+const DEFAULT_FENCE_MAP_MAX_ENTRIES: usize = 250_000;
+
/// Admission-time property size limits, in `pg_column_size` (JSONB
/// binary) terms — the same units as the `check_properties_size`
/// constraint they exist to enforce.
@@ -86,6 +92,19 @@ pub struct PersonHogLeaderService {
recovery: Arc<ChangelogRecovery>,
size_limits: PropertySizeLimits,
warnings: WarningsProducer,
+ /// The in-process copy of the fence state (see the fence module for the
+ /// durability model: the marks in Postgres are the source of truth,
+ /// this map exists so the write path rejects without a database read).
+ /// Mutated only under the per-key lock.
+ fences: FenceMap,
+ /// Ghost-fence recovery, derived from the fallback pool at
+ /// construction. Absent without one (dev fixtures) — ghost fences
+ /// then last until the partition changes hands, as before.
+ fence_healer: Option<Arc<FenceHealer>>,
+ /// Memory fuse for the fence map (see `fence_map_max_entries` in the
+ /// config for the full policy): at this many live fences, FencePerson
+ /// sheds new fences with RESOURCE_EXHAUSTED.
+ fence_map_max_entries: usize,
/// Present when broker-enforced epoch fencing is on; the write
/// path produces through the partition's transaction window.
fenced: Option<Arc<FencedChangelogProducers>>,
@@ -161,6 +180,7 @@ impl PersonHogLeaderService {
recovery: Arc<ChangelogRecovery>,
size_limits: PropertySizeLimits,
warnings: WarningsProducer,
+ fences: FenceMap,
fenced: Option<Arc<FencedChangelogProducers>>,
authority: Option<Arc<AuthorityClock>>,
emitted_versions: Arc<EmittedVersions>,
@@ -170,6 +190,9 @@ impl PersonHogLeaderService {
locks,
producer,
changelog_topic,
+ fence_healer: fallback
+ .as_ref()
+ .map(|f| Arc::new(FenceHealer::new(f.pool.clone(), Arc::clone(&fences)))),
fallback,
inflight,
num_partitions,
@@ -177,12 +200,22 @@ impl PersonHogLeaderService {
recovery,
size_limits,
warnings,
+ fences,
fenced,
authority,
emitted_versions,
+ fence_map_max_entries: DEFAULT_FENCE_MAP_MAX_ENTRIES,
}
}
+ /// Override the fence-map capacity (`fence_map_max_entries` in the
+ /// config). Separate from `new` so the many test fixtures keep the
+ /// default without threading one more argument through.
+ pub fn with_fence_capacity(mut self, max_entries: usize) -> Self {
+ self.fence_map_max_entries = max_entries;
+ self
+ }
+
/// Verify the router's routing decision against the request body: the
/// partition a request arrived on must equal the partition derived from
/// the key it carries. A mismatch means a client stamped wrong
@@ -207,6 +240,23 @@ impl PersonHogLeaderService {
Ok(())
}
+ /// The fence RPCs must never succeed on a pod that does not serve the
+ /// partition. A misrouted release that removed nothing and returned
+ /// OK would leave the real owner's fence in place while the saga
+ /// believes it released — a person frozen with no retry coming. The
+ /// handoff guard is not enough on its own: `release_partition`
+ /// unfences, so a pod that has already handed the partition off looks
+ /// unfenced. Rejecting sends the saga's retry to the current owner.
+ #[allow(clippy::result_large_err)]
+ fn validate_ownership(&self, partition: u32) -> Result<(), Status> {
+ if !self.cache.has_partition(partition) {
+ return Err(Status::failed_precondition(format!(
+ "partition {partition} is not served by this pod"
+ )));
+ }
+ Ok(())
+ }
+
fn record_cache_hit() {
counter!(
"personhog_leader_person_loads_total",
@@ -400,6 +450,251 @@ impl PersonHogLeaderService {
CacheLookup::PersonNotFound => self.recover_or_load(partition, key).await,
}
}
+
+ /// The shared tail of every document write: refuse unapplyable records,
+ /// produce to Kafka first, then dirty-mark and update the cache — so
+ /// readers only ever see durably committed state. The mark precedes the
+ /// cache insert: a reader that misses the cache in the gap sees the
+ /// mark and recovers this exact record from the changelog. Assumes the
+ /// caller holds the per-key lock.
+ async fn commit_document(
+ &self,
+ partition: u32,
+ cache_key: &PersonCacheKey,
+ person: CachedPerson,
+ ) -> Result<Person, Status> {
+ // A record the writer cannot bind must never reach the changelog —
+ // no consumer downstream can apply or repair it.
+ if let Err(reason) = assert_writeable(&person) {
+ counter!("personhog_leader_unwriteable_state_total").increment(1);
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ reason,
+ "refusing to produce an unapplyable changelog record"
+ );
+ return Err(Status::internal(format!(
+ "person state is not writeable: {reason}"
+ )));
+ }
+
+ let proto = cached_person_to_proto(&person);
+
+ // Re-check before producing, for the same reason the read path
+ // re-checks before answering: admission proves nothing about the
+ // moment the record lands. Between the check at entry and here a
+ // write can wait on the per-key lock behind another produce, and
+ // on a changelog recovery — long enough for a starved keepalive's
+ // stamp to age out, for the lease to expire at etcd, and for the
+ // coordinator to warm a successor past the point this record
+ // would land.
+ self.check_authority(partition)?;
+
+ // From here the record may reach the changelog whatever happens
+ // to this request — including the request simply ceasing to exist
+ // when the client's deadline expires. The guard is what makes the
+ // version un-reusable in that case.
+ let mut emitted = EmittedVersionGuard::new(
+ Arc::clone(&self.emitted_versions),
+ partition,
+ cache_key.clone(),
+ person.version,
+ );
+ emitted.emitting();
+
+ // Produce to Kafka first, then update the cache on success.
+ // Readers only ever see durably committed state.
+ let offset = if let Some(fenced) = &self.fenced {
+ match fenced.produce(partition, &proto).await {
+ Ok(offset) => offset,
+ // The broker fenced this pod: a newer owner holds the
+ // partition, so this claim is stale. FailedPrecondition
+ // is the admission fence's own vocabulary — the router
+ // classifies it as a bounce and re-resolves toward the
+ // real owner.
+ Err(e @ FencedProduceError::Fenced) => {
+ // Rejected at the broker, so the record does not
+ // exist and its version is free.
+ emitted.discarded();
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ "changelog producer fenced; rejecting write as stale owner"
+ );
+ // Deliberately no local reaction beyond failing the
+ // write. A broker fence proves *someone* newer
+ // initialized the transactional id, not that this pod
+ // lost the partition: a zombie waking inside its
+ // lease window re-acquires on the way to noticing it
+ // is dead, which fences the legitimate owner. So the
+ // fence is given up here as unusable and nothing
+ // more; `heal_fence`, on the next convergence to
+ // Serving, re-takes the epoch once the authority
+ // stamp confirms this pod's standing. Reads stay
+ // served meanwhile under the same stamp — the
+ // `check_authority` calls at admission and before
+ // answering are what refuse them once the claim
+ // lapses.
+ return Err(Status::failed_precondition(format!(
+ "partition ownership fenced: {e}"
+ )));
+ }
+ // This pod holds no producer for the partition — an
+ // ownership statement, in the same vocabulary the
+ // admission fence uses, so the router bounces and
+ // re-resolves instead of surfacing a hard error.
+ // The partition moved *and* this window's outcome was
+ // never settled. The router still needs the ownership
+ // answer, but the version cannot be handed back: the
+ // commit may have succeeded on an attempt librdkafka
+ // re-issued internally.
+ Err(e @ FencedProduceError::FencedUncertain(_)) => {
+ // Deliberately not settled: the partition moved and
+ // the window's own outcome never came back, so the
+ // record may or may not be in the log. Keeping the
+ // version spent is the whole of what safety needs.
+ counter!(
+ "personhog_leader_indeterminate_outcomes_total",
+ "fenced" => "true"
+ )
+ .increment(1);
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ error = %e,
+ "changelog producer fenced with an unknown outcome; version kept spent"
+ );
+ return Err(Status::failed_precondition(format!(
+ "partition ownership fenced: {e}"
+ )));
+ }
+ Err(e @ FencedProduceError::NotAcquired) => {
+ emitted.discarded();
+ tracing::warn!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ "no changelog fence held for partition; rejecting write"
+ );
+ return Err(Status::failed_precondition(format!(
+ "partition fence not held: {e}"
+ )));
+ }
+ // The commit's outcome is unknown, so this pod cannot
+ // say whether the record became visible. A caller
+ // retrying against a cache still holding the pre-write
+ // version would produce a second record at the same
+ // version as the one that may already have committed,
+ // and the writer's strict guard keeps whichever arrived
+ // first — which the floor prevents by holding the
+ // version spent.
+ Err(e @ FencedProduceError::Indeterminate(_)) => {
+ // Deliberately not settled: whether the record exists
+ // is exactly what is unknown, so the version stays
+ // spent and the retry derives past it.
+ counter!(
+ "personhog_leader_indeterminate_outcomes_total",
+ "fenced" => "false"
+ )
+ .increment(1);
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ error = %e,
+ "changelog commit outcome unknown; version kept spent"
+ );
+ return Err(Status::unknown(format!(
+ "person state may or may not have been stored: {e}"
+ )));
+ }
+ // The window aborted, so no record became visible: the
+ // write is safe to retry, and ABORTED is the code the
+ // clients actually retry on.
+ Err(e) => {
+ // The window aborted, so no record became visible and
+ // the version can be derived again.
+ emitted.discarded();
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ error = %e,
+ "failed to produce person state changelog (fenced path)"
+ );
+ return Err(Status::aborted(format!(
+ "failed to durably store person state: {e}"
+ )));
+ }
+ }
+ } else {
+ match produce_person_changelog(&self.producer, &self.changelog_topic, partition, &proto)
+ .await
+ {
+ Ok(offset) => offset,
+ Err(e) => {
+ // Deliberately not settled. This path collapses an
+ // enqueue that never left the client with a delivery
+ // that timed out after the broker may already have
+ // appended it, and idempotence is off by default, so
+ // the record's fate is genuinely unknown. Freeing the
+ // version here let a retry derive the same number and
+ // put a second record behind one that may be in the
+ // log — the writer's strict guard then keeps whichever
+ // arrived first and discards the acked one.
+ //
+ // The floor alone carries that: the next write
+ // derives past it whether or not the cache still
+ // holds the pre-write state. The entry stays, so
+ // reads may answer with a version older than the
+ // changelog until a later write for this person
+ // settles one. Evicting instead would resolve
+ // nothing — recovery reads the last *marked* offset,
+ // which is the previous write that did succeed — and
+ // would answer NOT_FOUND outright once that mark is
+ // pruned and no fallback pool is configured.
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ error = %e,
+ "failed to produce person state changelog"
+ );
+ return Err(Status::internal(format!(
+ "failed to durably store person state: {e}"
+ )));
+ }
+ }
+ };
+
+ // Mark before the cache insert: a reader that misses the cache in
+ // the gap sees the mark and recovers this exact record from the
+ // changelog. The mark outlives eviction and is pruned once the
+ // writer's committed offset passes it.
+ self.dirty_index.mark(
+ cache_key.clone(),
+ DirtyMark {
+ version: person.version,
+ offset,
+ partition,
+ },
+ );
+ self.cache.put(partition, cache_key.clone(), person);
+ // The cache carries the version now, so the floor has nothing
+ // left to say.
+ emitted.resolved();
+ Ok(proto)
+ }
+
+ /// The write path's fence conditional: an in-memory lookup and nothing
+ /// else. The map is authoritative here — a fence that outlives its op
+ /// is not the leader's to detect, because the op being unfinished is
+ /// exactly what a live mark means (see the fence module's ownership
+ /// model). Returns the fence to reject with, or None when the person
+ /// is writable. Assumes the caller holds the per-key lock.
+ fn check_fence(&self, cache_key: &PersonCacheKey) -> Option<FenceState> {
+ self.fences.get(cache_key).map(|entry| *entry.value())
+ }
}
/// Upper bound on the epoch-millisecond timestamps the leader will put in
@@ -459,6 +754,7 @@ fn cached_person_to_proto(p: &CachedPerson) -> Person {
is_identified: p.is_identified,
is_user_id: None,
last_seen_at: p.last_seen_at,
+ is_deleted: p.is_deleted,
}
}
@@ -504,6 +800,12 @@ impl PersonHogLeader for PersonHogLeaderService {
// answer, not the arrival, that has to be backed by ownership.
self.check_authority(partition)?;
+ // A recovered death document is an authoritative not-found: the
+ // person was destroyed and this entry closes its stream.
+ if person.is_deleted {
+ return Err(Status::not_found("person is destroyed"));
+ }
+
Ok(Response::new(GetPersonResponse {
person: Some(cached_person_to_proto(&person)),
}))
@@ -630,8 +932,28 @@ impl PersonHogLeader for PersonHogLeaderService {
));
}
+ // A person fenced by a live lifecycle op rejects writes until the
+ // fence is released; reads are unaffected. Checked under the
+ // per-key lock so a concurrent FencePerson cannot be missed.
+ if let Some(fence) = self.check_fence(&cache_key) {
+ counter!("personhog_leader_writes_fenced_total").increment(1);
+ // Off the request path: if this fence is a ghost (its op
+ // already settled), the healer drops it and a retry goes
+ // through.
+ if let Some(healer) = &self.fence_healer {
+ healer.maybe_heal(cache_key.clone(), fence);
+ }
+ return Err(fenced_status(&fence));
+ }
+
let person = self.lookup_or_load_locked(partition, &cache_key).await?;
+ // A destroyed person answers not-found — the caller re-resolves;
+ // post-death the distinct id may have been reborn as a new person.
+ if person.is_deleted {
+ return Err(Status::not_found("person is destroyed"));
+ }
+
// Compute property updates
let updates = compute_event_property_updates(
&req.event_name,
@@ -805,238 +1127,321 @@ impl PersonHogLeader for PersonHogLeaderService {
created_at: person.created_at,
version: base_version + 1,
is_identified: identified_now,
+ is_deleted: false,
last_seen_at: merged_last_seen,
approx_bytes,
};
- // Final applyability assertions on the identity fields, which
- // originate from earlier state rather than this request. A record
- // the writer cannot bind must never reach the changelog — no
- // consumer downstream can apply or repair it.
- if let Err(reason) = assert_writeable(&updated_person) {
- counter!("personhog_leader_unwriteable_state_total").increment(1);
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- reason,
- "refusing to produce an unapplyable changelog record"
- );
- return Err(Status::internal(format!(
- "person state is not writeable: {reason}"
- )));
- }
+ let proto = self
+ .commit_document(partition, &cache_key, updated_person)
+ .await?;
+ counter!("personhog_leader_updates_total", "outcome" => "updated").increment(1);
- let proto = cached_person_to_proto(&updated_person);
+ Ok(Response::new(UpdatePersonPropertiesResponse {
+ person: Some(proto),
+ updated: true,
+ }))
+ }
- // Re-check before producing, for the same reason the read path
- // re-checks before answering: admission proves nothing about the
- // moment the record lands. Between the check at entry and here a
- // write can wait on the per-key lock behind another produce, and
- // on a changelog recovery — long enough for a starved keepalive's
- // stamp to age out, for the lease to expire at etcd, and for the
- // coordinator to warm a successor past the point this record
- // would land.
- self.check_authority(partition)?;
+ async fn fence_person(
+ &self,
+ request: Request<FencePersonRequest>,
+ ) -> Result<Response<FencePersonResponse>, Status> {
+ let partition = partition_from_metadata(&request)?;
+ let req = request.into_inner();
+ self.validate_partition(partition, req.team_id, req.person_id)?;
+ let op_id = Uuid::parse_str(&req.op_id)
+ .map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;
+ let op_type = req.op_type();
+ if op_type == LifecycleOpType::Unspecified {
+ return Err(Status::invalid_argument("op_type must be specified"));
+ }
- // From here the record may reach the changelog whatever happens
- // to this request — including the request simply ceasing to exist
- // when the client's deadline expires. The guard is what makes the
- // version un-reusable in that case.
- let mut emitted = EmittedVersionGuard::new(
- Arc::clone(&self.emitted_versions),
- partition,
- cache_key.clone(),
- updated_person.version,
- );
- emitted.emitting();
+ // A fence installed anywhere but the current owner protects
+ // nothing: the map that gates writes is the owner's. Both guards
+ // are needed — ownership covers a pod that already handed the
+ // partition off (release unfences), the handoff guard covers the
+ // drain window before that. Refusing is what makes "a mark
+ // committed after the takeover scan arrives as a FencePerson call
+ // to the current owner" true: the saga's retry re-routes to the
+ // new owner.
+ self.validate_ownership(partition)?;
+ let Some(_inflight_guard) = self.inflight.try_begin(partition) else {
+ return Err(Status::failed_precondition(format!(
+ "partition {partition} is fenced for handoff; writes are rejected"
+ )));
+ };
- // Produce to Kafka first, then update the cache on success.
- // Readers only ever see durably committed state.
- let offset = if let Some(fenced) = &self.fenced {
- match fenced.produce(partition, &proto).await {
- Ok(offset) => offset,
- // The broker fenced this pod: a newer owner holds the
- // partition, so this claim is stale. FailedPrecondition
- // is the admission fence's own vocabulary — the router
- // classifies it as a bounce and re-resolves toward the
- // real owner.
- Err(e @ FencedProduceError::Fenced) => {
- // Rejected at the broker, so the record does not
- // exist and its version is free.
- emitted.discarded();
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- "changelog producer fenced; rejecting write as stale owner"
- );
- // Deliberately no local reaction beyond failing the
- // write. A broker fence proves *someone* newer
- // initialized the transactional id, not that this pod
- // lost the partition: a zombie waking inside its
- // lease window re-acquires on the way to noticing it
- // is dead, which fences the legitimate owner. So the
- // fence is given up here as unusable and nothing
- // more; `heal_fence`, on the next convergence to
- // Serving, re-takes the epoch once the authority
- // stamp confirms this pod's standing. Reads stay
- // served meanwhile under the same stamp — the
- // `check_authority` calls at admission and before
- // answering are what refuse them once the claim
- // lapses.
- return Err(Status::failed_precondition(format!(
- "partition ownership fenced: {e}"
- )));
+ let cache_key = PersonCacheKey {
+ team_id: req.team_id,
+ person_id: req.person_id,
+ };
+ let mutex = self
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let _guard = mutex.lock().await;
+
+ let refence = if let Some(entry) = self.fences.get(&cache_key) {
+ if entry.op_id != op_id {
+ // At most one lifecycle op holds a person; the loser backs
+ // off or aborts.
+ return Err(fenced_status(entry.value()));
+ }
+ true
+ } else {
+ false
+ };
+
+ // The memory fuse: the map has no eviction, so a surge of ops is
+ // bounded here, by shedding new fences. Re-seals are exempt — the
+ // person is already fenced, refusing frees nothing — and so is
+ // the takeover scan, whose marks are already live. The saga's
+ // retry absorbs the backpressure.
+ if !refence && self.fences.len() >= self.fence_map_max_entries {
+ counter!("personhog_leader_fences_total", "action" => "shed_capacity").increment(1);
+ return Err(Status::resource_exhausted(format!(
+ "fence map at capacity ({} live fences); retry later",
+ self.fence_map_max_entries
+ )));
+ }
+
+ // The seal: the newest cached state, captured under the same lock
+ // that admits writes — no gap for a write to sneak into. Fencing
+ // produces nothing and does not advance the version; the sealed
+ // version is the person's current one raised to the emitted
+ // floor, made final by the fence. The floor matters because a
+ // pre-fence write with an indeterminate outcome leaves a version
+ // spent above the cache's — sealing below it would derive the
+ // death document at a version that may already be live. A
+ // same-op re-fence takes this path too, re-sealing with fresh
+ // state (the saga's seal step is safe to repeat).
+ let person = self.lookup_or_load_locked(partition, &cache_key).await?;
+ if person.is_deleted {
+ return Err(Status::not_found("person is destroyed"));
+ }
+
+ let mut sealed = cached_person_to_proto(&person);
+ sealed.version = self
+ .emitted_versions
+ .floor_for(partition, &cache_key, person.version);
+
+ self.fences.insert(cache_key, FenceState { op_id, op_type });
+ counter!("personhog_leader_fences_total", "action" => "fenced").increment(1);
+
+ Ok(Response::new(FencePersonResponse {
+ sealed: Some(sealed),
+ }))
+ }
+
+ async fn release_fence(
+ &self,
+ request: Request<ReleaseFenceRequest>,
+ ) -> Result<Response<ReleaseFenceResponse>, Status> {
+ let partition = partition_from_metadata(&request)?;
+ let req = request.into_inner();
+ self.validate_partition(partition, req.team_id, req.person_id)?;
+ let op_id = Uuid::parse_str(&req.op_id)
+ .map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;
+ let outcome = req.outcome();
+
+ // Both outcomes: a release that removed nothing and returned OK
+ // would leave the real owner's fence standing while the saga
+ // believes it released — a person frozen with no retry coming.
+ self.validate_ownership(partition)?;
+
+ let cache_key = PersonCacheKey {
+ team_id: req.team_id,
+ person_id: req.person_id,
+ };
+ let mutex = self
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let _guard = mutex.lock().await;
+
+ // Releasing another op's fence would break that op's seal.
+ if let Some(entry) = self.fences.get(&cache_key) {
+ if entry.op_id != op_id {
+ return Err(fenced_status(entry.value()));
+ }
+ }
+
+ match outcome {
+ ReleaseOutcome::Committed => {
+ // 0 is a legitimate sealed version (a fresh stub's),
+ // which is why the field is explicitly optional in the proto.
+ let Some(sealed_version) = req.sealed_version else {
+ return Err(Status::invalid_argument(
+ "sealed_version is required for a committed release",
+ ));
+ };
+ if sealed_version < 0 {
+ return Err(Status::invalid_argument(
+ "sealed_version must not be negative",
+ ));
}
- // This pod holds no producer for the partition — an
- // ownership statement, in the same vocabulary the
- // admission fence uses, so the router bounces and
- // re-resolves instead of surfacing a hard error.
- // The partition moved *and* this window's outcome was
- // never settled. The router still needs the ownership
- // answer, but the version cannot be handed back: the
- // commit may have succeeded on an attempt librdkafka
- // re-issued internally.
- Err(e @ FencedProduceError::FencedUncertain(_)) => {
- // Deliberately not settled: the partition moved and
- // the window's own outcome never came back, so the
- // record may or may not be in the log. Keeping the
- // version spent is the whole of what safety needs.
- counter!(
- "personhog_leader_indeterminate_outcomes_total",
- "fenced" => "true"
- )
- .increment(1);
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- error = %e,
- "changelog producer fenced with an unknown outcome; version kept spent"
- );
- return Err(Status::failed_precondition(format!(
- "partition ownership fenced: {e}"
- )));
+ if req.created_at <= 0 {
+ return Err(Status::invalid_argument(
+ "created_at is required for a committed release",
+ ));
}
- Err(e @ FencedProduceError::NotAcquired) => {
- emitted.discarded();
- tracing::warn!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- "no changelog fence held for partition; rejecting write"
- );
+ if Uuid::parse_str(&req.person_uuid).is_err() {
+ return Err(Status::invalid_argument(
+ "person_uuid must be a valid UUID for a committed release",
+ ));
+ }
+ // Producing to the changelog must respect the handoff
+ // write freeze like any write.
+ let Some(_inflight_guard) = self.inflight.try_begin(partition) else {
return Err(Status::failed_precondition(format!(
- "partition fence not held: {e}"
+ "partition {partition} is fenced for handoff; writes are rejected"
)));
+ };
+
+ // Release must stay idempotent for the saga's retry and the
+ // sweeper, so a person the leader cannot load anymore is
+ // tolerated.
+ let current = match self.lookup_or_load_locked(partition, &cache_key).await {
+ Ok(person) => Some(person),
+ Err(status) if status.code() == tonic::Code::NotFound => None,
+ Err(status) => return Err(status),
+ };
+
+ // Duplicate release: the death document already exists;
+ // producing another would only bump the version.
+ if current.as_ref().is_some_and(|p| p.is_deleted) {
+ self.fences.remove(&cache_key);
+ return Ok(Response::new(ReleaseFenceResponse {}));
}
- // The commit's outcome is unknown, so this pod cannot
- // say whether the record became visible. A caller
- // retrying against a cache still holding the pre-write
- // version would produce a second record at the same
- // version as the one that may already have committed,
- // and the writer's strict guard keeps whichever arrived
- // first — which the floor prevents by holding the
- // version spent.
- Err(e @ FencedProduceError::Indeterminate(_)) => {
- // Deliberately not settled: whether the record exists
- // is exactly what is unknown, so the version stays
- // spent and the retry derives past it.
- counter!(
- "personhog_leader_indeterminate_outcomes_total",
- "fenced" => "false"
- )
- .increment(1);
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- error = %e,
- "changelog commit outcome unknown; version kept spent"
- );
- return Err(Status::unknown(format!(
- "person state may or may not have been stored: {e}"
- )));
+
+ // The death document's identity comes from the request (a
+ // cold leader has nothing else), so when the leader DOES
+ // hold the person, the request must agree with it — the
+ // writer upserts uuid verbatim, and a mismatched request
+ // would rewrite the row's identity on its way out.
+ if let Some(person) = &current {
+ if person.uuid != req.person_uuid {
+ return Err(Status::failed_precondition(
+ "person_uuid does not match the person being released",
+ ));
+ }
}
- // The window aborted, so no record became visible: the
- // write is safe to retry, and ABORTED is the code the
- // clients actually retry on.
- Err(e) => {
- // The window aborted, so no record became visible and
- // the version can be derived again.
- emitted.discarded();
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- error = %e,
- "failed to produce person state changelog (fenced path)"
- );
- return Err(Status::aborted(format!(
- "failed to durably store person state: {e}"
- )));
+
+ // The mark row — the fence's source of truth — must vouch
+ // for the op before anything is destroyed. The in-memory
+ // fence is not enough: FencePerson never verified the op
+ // either, so the request (plus a fence it installed
+ // itself) must never be sufficient to produce a death
+ // document. Unverifiable requests are refused — fail
+ // closed.
+ let Some(fallback) = &self.fallback else {
+ return Err(Status::failed_precondition(
+ "no lifecycle database configured; refusing to produce a death document",
+ ));
+ };
+ match mark_status(&fallback.pool, op_id, req.team_id, req.person_id).await {
+ // A live mark: the op holds the person; proceed.
+ Ok(Some(status)) if status == "marked" || status == "sealed" => {}
+ // The mark already settled as deleted: this release
+ // already happened and the tombstone is durable;
+ // absorb the retry.
+ Ok(Some(status)) if status == "deleted" => {
+ self.fences.remove(&cache_key);
+ return Ok(Response::new(ReleaseFenceResponse {}));
+ }
+ Ok(_) => {
+ counter!("personhog_leader_fences_total", "action" => "release_unverified")
+ .increment(1);
+ return Err(Status::failed_precondition(
+ "op holds no live mark for this person; \
+ refusing to produce a death document",
+ ));
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "mark verification failed; rejecting (fail closed)");
+ return Err(Status::unavailable(
+ "could not verify the lifecycle op against its mark; retry",
+ ));
+ }
}
- }
- } else {
- match produce_person_changelog(&self.producer, &self.changelog_topic, partition, &proto)
- .await
- {
- Ok(offset) => offset,
- Err(e) => {
- // Deliberately not settled. This path collapses an
- // enqueue that never left the client with a delivery
- // that timed out after the broker may already have
- // appended it, and idempotence is off by default, so
- // the record's fate is genuinely unknown. Freeing the
- // version here let a retry derive the same number and
- // put a second record behind one that may be in the
- // log — the writer's strict guard then keeps whichever
- // arrived first and discards the acked one.
- //
- // The floor alone carries that: the next write
- // derives past it whether or not the cache still
- // holds the pre-write state. The entry stays, so
- // reads may answer with a version older than the
- // changelog until a later write for this person
- // settles one. Evicting instead would resolve
- // nothing — recovery reads the last *marked* offset,
- // which is the previous write that did succeed — and
- // would answer NOT_FOUND outright once that mark is
- // pruned and no fallback pool is configured.
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- error = %e,
- "failed to produce person state changelog"
- );
- return Err(Status::internal(format!(
- "failed to durably store person state: {e}"
- )));
+
+ if !self.dirty_index.can_admit(&cache_key) {
+ counter!("personhog_leader_writes_shed_total", "reason" => "dirty_index_full")
+ .increment(1);
+ return Err(Status::resource_exhausted(
+ "dirty index at capacity: the writer is behind and this death document \
+ cannot be tracked; retry later",
+ ));
}
+ // The death version: sealed + 1 per the RFC — the fence
+ // makes the sealed version final. The max over the current
+ // version and the emitted floor is defense in depth until
+ // broker producer fencing lands (a deposed leader's
+ // produce could otherwise still advance the version, and
+ // an indeterminate one leaves a version spent that the
+ // cache never learned of); a cold leader with no state
+ // falls back to the sealed version carried by the
+ // request, reproducing the death document
+ // deterministically.
+ let base_version = self.emitted_versions.floor_for(
+ partition,
+ &cache_key,
+ current
+ .as_ref()
+ .map(|p| p.version)
+ .unwrap_or(0)
+ .max(sealed_version),
+ );
+ let death_version = base_version.checked_add(1).ok_or_else(|| {
+ Status::invalid_argument("sealed_version leaves no room for the death version")
+ })?;
+ let death = CachedPerson {
+ id: req.person_id,
+ uuid: req.person_uuid.clone(),
+ team_id: req.team_id,
+ properties: serde_json::Value::Object(serde_json::Map::new()),
+ // The sealed value, not the cached one: cold and warm
+ // leaders must produce the same document.
+ created_at: req.created_at,
+ version: death_version,
+ is_identified: false,
+ is_deleted: true,
+ last_seen_at: None,
+ approx_bytes: approx_person_bytes(jsonb_column_size(
+ &serde_json::Value::Object(serde_json::Map::new()),
+ )),
+ };
+ self.commit_document(partition, &cache_key, death).await?;
+ // The death document stays in the cache (commit_document
+ // put it there): an is_deleted entry answers reads and
+ // writes with an authoritative not-found from memory, the
+ // same way a recovered death document does. Removing it
+ // would only re-derive it — the next attempt recovers the
+ // death record via the dirty mark and re-installs it — and
+ // once the mark is pruned every attempt would fall through
+ // to a PG read instead.
+ self.fences.remove(&cache_key);
+ counter!("personhog_leader_fences_total", "action" => "released_committed")
+ .increment(1);
}
- };
-
- // Mark before the cache insert: a reader that misses the cache in
- // the gap sees the mark and recovers this exact record from the
- // changelog. The mark outlives eviction and is pruned once the
- // writer's committed offset passes it.
- self.dirty_index.mark(
- cache_key.clone(),
- DirtyMark {
- version: updated_person.version,
- offset,
- partition,
- },
- );
- self.cache.put(partition, cache_key, updated_person);
- // The cache carries the version now, so the floor has nothing
- // left to say.
- emitted.resolved();
- counter!("personhog_leader_updates_total", "outcome" => "updated").increment(1);
+ ReleaseOutcome::Aborted => {
+ // The op backed out: drop the fence, keep the entry,
+ // produce nothing. The person resumes normal life.
+ self.fences.remove(&cache_key);
+ counter!("personhog_leader_fences_total", "action" => "released_aborted")
+ .increment(1);
+ }
+ ReleaseOutcome::Unspecified => {
+ return Err(Status::invalid_argument("outcome must be specified"));
+ }
+ }
- Ok(Response::new(UpdatePersonPropertiesResponse {
- person: Some(proto),
- updated: true,
- }))
+ Ok(Response::new(ReleaseFenceResponse {}))
}
}
@@ -1103,6 +1508,7 @@ mod tests {
),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
Arc::new(EmittedVersions::new(1_000_000)),
@@ -1191,6 +1597,7 @@ mod tests {
created_at: 0,
version: 1,
is_identified: false,
+ is_deleted: false,
last_seen_at: None,
approx_bytes: 64,
},
@@ -1256,6 +1663,7 @@ mod tests {
created_at: 0,
version: 1,
is_identified: false,
+ is_deleted: false,
last_seen_at: None,
approx_bytes: 64,
},
@@ -1357,6 +1765,7 @@ mod tests {
created_at: 0,
version: 1,
is_identified: false,
+ is_deleted: false,
last_seen_at: None,
approx_bytes: 64,
},
@@ -1402,6 +1811,7 @@ mod tests {
created_at: 0,
version: 1,
is_identified: false,
+ is_deleted: false,
last_seen_at: None,
approx_bytes: 64,
},
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 93fac3acf6b2..8a6b55418dd1 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -363,6 +363,9 @@ pub async fn start_leader_pod(
Arc::clone(&inflight),
Arc::clone(&dirty_index),
warming,
+ Arc::new(dashmap::DashMap::new()),
+ None,
+ NUM_PARTITIONS,
pools,
None,
None,
@@ -398,6 +401,7 @@ pub async fn start_leader_pod(
recovery,
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(dashmap::DashMap::new()),
None,
// A live claim rather than none, so the lease gate on the read
// and write paths is exercised by every test built on this
@@ -459,6 +463,9 @@ pub async fn start_leader_pod_with_lease_ttl(
Arc::clone(&inflight),
Arc::clone(&dirty_index),
warming,
+ Arc::new(dashmap::DashMap::new()),
+ None,
+ NUM_PARTITIONS,
pools,
None,
None,
@@ -495,6 +502,7 @@ pub async fn start_leader_pod_with_lease_ttl(
recovery,
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(dashmap::DashMap::new()),
None,
None,
std::sync::Arc::clone(&emitted_versions),
@@ -530,6 +538,19 @@ pub async fn create_leader_client(addr: SocketAddr) -> PersonHogLeaderClient<Cha
PersonHogLeaderClient::connect(url).await.unwrap()
}
+/// A team id no other test shares, however the tests are scheduled.
+/// Random rather than counter- or clock-derived: nextest runs each test
+/// in its own process, so any per-process counter or seconds-based salt
+/// hands the same id to tests launched in the same second. Tests that
+/// write shared Postgres state (lifecycle marks, person rows) key it by
+/// team, so a unique team makes them collision-free and self-contained
+/// with no cleanup ordering to get right. Stays inside the team_id
+/// column's integer range.
+#[allow(dead_code)]
+pub fn unique_team_id() -> i64 {
+ (uuid::Uuid::new_v4().as_u128() % 900_000_000 + 100_000_000) as i64
+}
+
pub fn seed_person(cache: &PartitionedCache, partition: u32, person: CachedPerson) {
let key = PersonCacheKey {
team_id: person.team_id,
@@ -547,6 +568,7 @@ pub fn test_cached_person() -> CachedPerson {
created_at: 1700000000,
version: 1,
is_identified: false,
+ is_deleted: false,
last_seen_at: None,
approx_bytes: approx_person_bytes(64),
}
@@ -587,6 +609,7 @@ pub async fn start_leader_with_pg_fallback(
test_recovery(&mock_cluster.bootstrap_servers()),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(dashmap::DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -710,6 +733,9 @@ fn handoff_handler_with(
inflight,
Arc::new(DirtyIndex::new(1_000_000)),
warming,
+ Arc::new(dashmap::DashMap::new()),
+ None,
+ NUM_PARTITIONS,
Arc::new(personhog_leader::warming::WarmClientPools::new(
&test_kafka_config(),
"test",
diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rs
new file mode 100644
index 000000000000..550076f9d2b8
--- /dev/null
+++ b/rust/personhog-leader/tests/fence_integration.rs
@@ -0,0 +1,1164 @@
+//! Lifecycle fence semantics over the real gRPC surface: the fence is a
+//! document write, so these tests assert both the RPC behavior and the
+//! changelog records it produces.
+
+mod common;
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use dashmap::DashMap;
+
+use common::{
+ create_leader_client, create_test_kafka, seed_person, test_cached_person, test_recovery,
+ unique_team_id, CHANGELOG_TOPIC, NUM_PARTITIONS,
+};
+use personhog_common::partitioning::partition_for_person;
+use personhog_leader::cache::{CachedPerson, DirtyIndex, PartitionedCache, PersonCacheKey};
+use personhog_leader::emitted::EmittedVersions;
+use personhog_leader::fence::{FENCED_METADATA_KEY, FENCED_OP_ID_METADATA_KEY};
+use personhog_leader::inflight::InflightTracker;
+use personhog_leader::pg::PgFallback;
+use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
+use personhog_leader::warnings::WarningsProducer;
+use personhog_proto::personhog::leader::v1::person_hog_leader_client::PersonHogLeaderClient;
+use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
+use personhog_proto::personhog::types::v1::{
+ FencePersonRequest, GetPersonRequest, LifecycleOpType, Person, ReleaseFenceRequest,
+ ReleaseOutcome, UpdatePersonPropertiesRequest,
+};
+use prost::Message;
+use rdkafka::consumer::{BaseConsumer, Consumer};
+use rdkafka::{ClientConfig, Message as KafkaMessage, TopicPartitionList};
+use tokio::net::TcpListener;
+use tokio_util::sync::CancellationToken;
+use tonic::transport::Channel;
+use tonic::transport::Server;
+use tonic::{Code, Request};
+use uuid::Uuid;
+
+fn with_partition<T>(req: T, partition: u32) -> Request<T> {
+ let mut request = Request::new(req);
+ request
+ .metadata_mut()
+ .insert("x-partition", partition.to_string().parse().unwrap());
+ request
+}
+
+fn fence_request(team_id: i64, person_id: i64, op_id: &Uuid) -> FencePersonRequest {
+ FencePersonRequest {
+ team_id,
+ person_id,
+ op_id: op_id.to_string(),
+ op_type: LifecycleOpType::Delete.into(),
+ }
+}
+
+fn update_request(team_id: i64, person_id: i64) -> UpdatePersonPropertiesRequest {
+ UpdatePersonPropertiesRequest {
+ team_id,
+ person_id,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "after-fence"})).unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ is_identified: None,
+ last_seen_at: None,
+ }
+}
+
+/// A leader service over a mock Kafka cluster with one seeded person, served
+/// on a local socket. Returns the client, the seeded person's partition, its
+/// id, and the consumer-facing bootstrap for changelog assertions.
+struct FenceHarness {
+ client: PersonHogLeaderClient<Channel>,
+ team_id: i64,
+ partition: u32,
+ person_id: i64,
+ bootstrap: String,
+ cache: Arc<PartitionedCache>,
+ inflight: Arc<InflightTracker>,
+ emitted_versions: Arc<EmittedVersions>,
+ _cancel: CancellationToken,
+ _mock_cluster:
+ rdkafka::mocking::MockCluster<'static, rdkafka::producer::DefaultProducerContext>,
+}
+
+async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback>) -> FenceHarness {
+ let (mock_cluster, kafka_producer) = create_test_kafka().await;
+ let bootstrap = mock_cluster.bootstrap_servers();
+
+ // Every harness gets its own team, so concurrent tests — and leftover
+ // rows from a failed earlier run — can never stomp on each other's
+ // lifecycle marks.
+ let team_id = unique_team_id();
+ seed.team_id = team_id;
+ let person_id = seed.id;
+ let partition = partition_for_person(team_id, person_id, NUM_PARTITIONS);
+
+ let cache = Arc::new(PartitionedCache::new(1 << 20));
+ let inflight = Arc::new(InflightTracker::new());
+ let emitted_versions = Arc::new(EmittedVersions::new(1_000_000));
+ // Recovery consumes the same mock cluster so a post-death cache miss
+ // can recover the death document.
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer.clone(),
+ CHANGELOG_TOPIC.to_string(),
+ fallback,
+ Arc::new(DashMap::new()),
+ Arc::clone(&inflight),
+ NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(&bootstrap),
+ PropertySizeLimits::new(655360, 524288),
+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
+ None,
+ None,
+ Arc::clone(&emitted_versions),
+ );
+
+ cache.create_partition(partition);
+ seed_person(&cache, partition, seed);
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+
+ FenceHarness {
+ client: create_leader_client(addr).await,
+ team_id,
+ partition,
+ person_id,
+ bootstrap,
+ cache,
+ inflight,
+ emitted_versions,
+ _cancel: cancel,
+ _mock_cluster: mock_cluster,
+ }
+}
+
+/// All changelog records currently on the person's partition, oldest first.
+fn changelog_records(harness: &FenceHarness) -> Vec<Person> {
+ let consumer: BaseConsumer = ClientConfig::new()
+ .set("bootstrap.servers", &harness.bootstrap)
+ .set("group.id", format!("fence-test-{}", Uuid::new_v4()))
+ .create()
+ .expect("failed to create consumer");
+ let mut tpl = TopicPartitionList::new();
+ tpl.add_partition_offset(
+ CHANGELOG_TOPIC,
+ harness.partition as i32,
+ rdkafka::Offset::Beginning,
+ )
+ .unwrap();
+ consumer.assign(&tpl).unwrap();
+
+ // The first poll can come back empty while the assignment settles, so
+ // keep polling until the partition has been quiet after producing at
+ // least one record, bounded by an overall deadline.
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ let mut records = Vec::new();
+ loop {
+ match consumer.poll(Duration::from_millis(300)) {
+ Some(result) => {
+ let msg = result.expect("kafka error");
+ records
+ .push(Person::decode(msg.payload().unwrap()).expect("decode changelog record"));
+ }
+ None if !records.is_empty() || std::time::Instant::now() >= deadline => break,
+ None => {}
+ }
+ }
+ records
+}
+
+#[tokio::test]
+async fn fencing_seals_and_blocks_writes_until_an_aborted_release() {
+ let mut harness = start_fence_harness(test_cached_person(), None).await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let op = Uuid::now_v7();
+
+ // Fence + seal in one call: the sealed state is the person's current
+ // state — fencing produces nothing and does not advance the version.
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .expect("sealed state returned");
+ assert_eq!(
+ sealed.version, 1,
+ "the seal is the current version, not a write"
+ );
+
+ // Writes are rejected with the typed error while the fence holds.
+ let status = harness
+ .client
+ .update_person_properties(with_partition(
+ update_request(team_id, person_id),
+ partition,
+ ))
+ .await
+ .expect_err("fenced person rejects writes");
+ assert_eq!(status.code(), Code::FailedPrecondition);
+ assert_eq!(
+ status.metadata().get(FENCED_METADATA_KEY).unwrap(),
+ "delete"
+ );
+ assert_eq!(
+ status.metadata().get(FENCED_OP_ID_METADATA_KEY).unwrap(),
+ op.to_string().as_str()
+ );
+
+ // Reads are unaffected.
+ let read = harness
+ .client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id,
+ person_id,
+ read_options: None,
+ },
+ partition,
+ ))
+ .await
+ .expect("reads flow while fenced");
+ assert_eq!(read.into_inner().person.unwrap().version, 1);
+
+ // Re-fencing with the same op re-seals with fresh state (the saga's
+ // seal step is safe to repeat); a different op is rejected.
+ let resealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("same-op re-fence succeeds")
+ .into_inner()
+ .sealed
+ .unwrap();
+ assert_eq!(
+ resealed.version, 1,
+ "nothing changed, so the fresh seal matches"
+ );
+
+ let other_op = Uuid::now_v7();
+ let status = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &other_op),
+ partition,
+ ))
+ .await
+ .expect_err("at most one op holds a person");
+ assert_eq!(status.code(), Code::FailedPrecondition);
+
+ // An aborted release clears the fence with a document write and the
+ // person resumes normal life.
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid: String::new(),
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Aborted.into(),
+ sealed_version: None,
+ created_at: 0,
+ },
+ partition,
+ ))
+ .await
+ .expect("aborted release succeeds");
+
+ let updated = harness
+ .client
+ .update_person_properties(with_partition(
+ update_request(team_id, person_id),
+ partition,
+ ))
+ .await
+ .expect("writes resume after the aborted release")
+ .into_inner();
+ assert!(updated.updated);
+ let person = updated.person.unwrap();
+ assert_eq!(
+ person.version, 2,
+ "fencing and the aborted release left no trace in the version"
+ );
+}
+
+#[tokio::test]
+async fn a_committed_release_produces_the_death_document_above_every_version() {
+ let pool = common::create_persons_pool().await;
+ let mut harness = start_fence_harness(
+ test_cached_person(),
+ Some(PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ }),
+ )
+ .await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let person_uuid = test_cached_person().uuid;
+ let op = Uuid::now_v7();
+
+ // The mark rows the committed release verifies against — committed by
+ // the saga before the fence in the real flow.
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .execute(&pool)
+ .await
+ .expect("insert op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'sealed')",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .expect("insert mark");
+
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .unwrap();
+ let sealed_version = sealed.version;
+
+ // Simulate a write that slipped through an unfenced window (leader
+ // amnesia after a handoff): the cached person advances past the seal
+ // without the fence.
+ seed_person(
+ &harness.cache,
+ partition,
+ CachedPerson {
+ team_id,
+ version: sealed_version + 3,
+ ..test_cached_person()
+ },
+ );
+
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid: person_uuid.clone(),
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sealed_version),
+ created_at: sealed.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("committed release succeeds");
+
+ let records = changelog_records(&harness);
+ let death = records.last().expect("death document produced");
+ assert!(death.is_deleted);
+ assert_eq!(
+ death.version,
+ sealed_version + 4,
+ "death version outranks the slipped write, not just the seal"
+ );
+ assert_eq!(death.uuid, person_uuid);
+ assert_eq!(
+ death.created_at, sealed.created_at,
+ "the death document carries the sealed creation time, not a cold-path zero"
+ );
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&death.properties).unwrap(),
+ serde_json::json!({}),
+ "death documents carry no properties"
+ );
+
+ // The death document stays cached, so reads answer an authoritative
+ // not-found from memory — no changelog recovery, no PG fallback.
+ match harness.cache.get(
+ partition,
+ &personhog_leader::cache::PersonCacheKey { team_id, person_id },
+ ) {
+ personhog_leader::cache::CacheLookup::Found(entry) => {
+ assert!(entry.is_deleted, "the cached entry is the death document")
+ }
+ _ => panic!("the death document must stay cached"),
+ }
+ let status = harness
+ .client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id,
+ person_id,
+ read_options: None,
+ },
+ partition,
+ ))
+ .await
+ .expect_err("a destroyed person reads as not-found");
+ assert_eq!(status.code(), Code::NotFound);
+
+ // A duplicate committed release is absorbed without a second death
+ // document.
+ let records_before = changelog_records(&harness).len();
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sealed_version),
+ created_at: sealed.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("duplicate release is idempotent");
+ assert_eq!(changelog_records(&harness).len(), records_before);
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup");
+}
+
+/// A pre-fence write with an indeterminate produce outcome spends a
+/// version the cache never learned of. The seal must cover it: sealed
+/// below the spent version, the death document would derive at a version
+/// that may already be live in the changelog.
+#[tokio::test]
+async fn the_seal_covers_versions_emitted_without_an_outcome() {
+ let mut harness = start_fence_harness(test_cached_person(), None).await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+
+ let spent = test_cached_person().version + 4;
+ harness.emitted_versions.raise_for_test(
+ partition,
+ PersonCacheKey { team_id, person_id },
+ spent,
+ );
+
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &Uuid::now_v7()),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .unwrap();
+ assert_eq!(
+ sealed.version, spent,
+ "the seal must cover the emitted floor, not just the cache's version"
+ );
+}
+
+/// The release-side counterpart: a post-seal write that slipped through an
+/// unfenced window (leader amnesia after a handoff) with an indeterminate
+/// outcome raises the floor without touching the cache. The death version
+/// must clear that floor, or the death document lands at the same version
+/// as a record that may already be in the changelog.
+#[tokio::test]
+async fn a_committed_release_derives_the_death_version_above_the_emitted_floor() {
+ let pool = common::create_persons_pool().await;
+ let mut harness = start_fence_harness(
+ test_cached_person(),
+ Some(PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ }),
+ )
+ .await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let person_uuid = test_cached_person().uuid;
+ let op = Uuid::now_v7();
+
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .execute(&pool)
+ .await
+ .expect("insert op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'sealed')",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .expect("insert mark");
+
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .unwrap();
+
+ let spent = sealed.version + 3;
+ harness.emitted_versions.raise_for_test(
+ partition,
+ PersonCacheKey { team_id, person_id },
+ spent,
+ );
+
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sealed.version),
+ created_at: sealed.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("committed release succeeds");
+
+ let records = changelog_records(&harness);
+ let death = records.last().expect("death document produced");
+ assert!(death.is_deleted);
+ assert_eq!(
+ death.version,
+ spent + 1,
+ "the death version must clear the emitted floor, not just the seal"
+ );
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup");
+}
+
+/// A fresh person stub is created at version 0, so 0 is a sealed version
+/// the committed release must accept — a presence check that treats 0 as
+/// "unset" fences the stub forever.
+#[tokio::test]
+async fn a_stub_sealed_at_version_zero_can_be_released() {
+ let pool = common::create_persons_pool().await;
+ let stub = CachedPerson {
+ version: 0,
+ ..test_cached_person()
+ };
+ let mut harness = start_fence_harness(
+ stub,
+ Some(PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ }),
+ )
+ .await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let op = Uuid::now_v7();
+
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .execute(&pool)
+ .await
+ .expect("insert op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'sealed')",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .expect("insert mark");
+
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .unwrap();
+ assert_eq!(sealed.version, 0, "the stub seals at its real version");
+
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid: sealed.uuid.clone(),
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(0),
+ created_at: sealed.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("a sealed version of 0 is presence, not absence");
+
+ let records = changelog_records(&harness);
+ let death = records.last().expect("death document produced");
+ assert!(death.is_deleted);
+ assert_eq!(death.version, 1, "the death version clears the seal");
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup");
+}
+
+/// A fence whose op has already settled its mark row is a ghost: its
+/// release was acked elsewhere and no retry is coming. A write rejected
+/// by it must trigger the lazy heal, so a retry goes through instead of
+/// the person staying frozen until the partition changes hands.
+#[tokio::test]
+async fn a_ghost_fence_heals_after_a_rejected_write() {
+ let pool = common::create_persons_pool().await;
+ let mut harness = start_fence_harness(
+ test_cached_person(),
+ Some(PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ }),
+ )
+ .await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let op = Uuid::now_v7();
+
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .execute(&pool)
+ .await
+ .expect("insert op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'sealed')",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .expect("insert mark");
+
+ harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds");
+
+ // The op settles (release acked to the saga, mark rows cleaned up)
+ // without this leader hearing about it — the ghost scenario.
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("settle the op");
+
+ // The first write bounces on the ghost and triggers the heal; a
+ // retry then goes through once the background check drops the fence.
+ let status = harness
+ .client
+ .update_person_properties(with_partition(
+ update_request(team_id, person_id),
+ partition,
+ ))
+ .await
+ .expect_err("the first write still bounces on the ghost");
+ assert_eq!(status.code(), Code::FailedPrecondition);
+
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
+ loop {
+ match harness
+ .client
+ .update_person_properties(with_partition(
+ update_request(team_id, person_id),
+ partition,
+ ))
+ .await
+ {
+ Ok(_) => break,
+ Err(status) if status.code() == Code::FailedPrecondition => {
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "the ghost fence was never healed"
+ );
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ Err(other) => panic!("unexpected rejection: {other}"),
+ }
+ }
+}
+
+/// The fail-closed half of the committed release: the request — even with
+/// a fence the caller installed itself — is never enough to destroy a
+/// person. Without a live mark row vouching for the op, the release is
+/// refused and the person is untouched.
+#[tokio::test]
+async fn a_committed_release_without_a_live_mark_is_refused() {
+ let pool = common::create_persons_pool().await;
+ let mut harness = start_fence_harness(
+ test_cached_person(),
+ Some(PgFallback {
+ pool,
+ table: "posthog_person".to_string(),
+ }),
+ )
+ .await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let op = Uuid::now_v7();
+
+ // Fencing succeeds — the fence RPC does not verify the op…
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .expect("sealed state returned");
+
+ // …but the committed release must find the live mark, and there is
+ // none: no lifecycle_op_person row was ever committed for this op.
+ let status = harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid: test_cached_person().uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sealed.version),
+ created_at: sealed.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect_err("a release with no live mark is refused");
+ assert_eq!(status.code(), Code::FailedPrecondition);
+
+ // The person is untouched: had a death document been produced, the
+ // entry would have been evicted and this read would answer not-found.
+ let read = harness
+ .client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id,
+ person_id,
+ read_options: None,
+ },
+ partition,
+ ))
+ .await
+ .expect("the person is still alive");
+ assert_eq!(read.into_inner().person.unwrap().version, sealed.version);
+}
+
+/// Neither fence RPC may succeed on a pod that does not serve the
+/// partition. A release that removed nothing and returned OK would leave
+/// the real owner's fence standing while the saga believes it released —
+/// a person frozen with no retry coming.
+#[tokio::test]
+async fn the_fence_rpcs_refuse_a_partition_this_pod_does_not_serve() {
+ let mut harness = start_fence_harness(test_cached_person(), None).await;
+ let team_id = harness.team_id;
+ // A person on a partition the harness never created.
+ let mut foreign_id: i64 = harness.person_id + 1;
+ while partition_for_person(team_id, foreign_id, NUM_PARTITIONS) == harness.partition {
+ foreign_id += 1;
+ }
+ let foreign_partition = partition_for_person(team_id, foreign_id, NUM_PARTITIONS);
+ let op = Uuid::now_v7();
+
+ let status = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, foreign_id, &op),
+ foreign_partition,
+ ))
+ .await
+ .expect_err("fencing an unserved partition is refused");
+ assert_eq!(status.code(), Code::FailedPrecondition);
+
+ let status = harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id: foreign_id,
+ person_uuid: String::new(),
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Aborted.into(),
+ sealed_version: None,
+ created_at: 0,
+ },
+ foreign_partition,
+ ))
+ .await
+ .expect_err("an aborted release must not vacuously succeed elsewhere");
+ assert_eq!(status.code(), Code::FailedPrecondition);
+}
+
+/// A drained (deposed) pod must refuse FencePerson: a fence accepted
+/// there lands in a map the new owner never consults and is silently
+/// discarded at release, leaving the saga with a seal that protects
+/// nothing. The refusal is what forces the saga's retry onto the current
+/// owner.
+#[tokio::test]
+async fn fencing_is_refused_while_the_partition_is_handoff_fenced() {
+ let mut harness = start_fence_harness(test_cached_person(), None).await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let op = Uuid::now_v7();
+
+ harness.inflight.fence(partition);
+ let status = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect_err("a handoff-fenced partition refuses FencePerson");
+ assert_eq!(status.code(), Code::FailedPrecondition);
+ assert!(
+ status.metadata().get(FENCED_METADATA_KEY).is_none(),
+ "a handoff rejection is not a person-fence rejection"
+ );
+
+ // Re-admission (a cancelled handoff, or a fresh warm) restores fencing.
+ harness.inflight.unfence(partition);
+ harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fencing resumes once the partition is re-admitted");
+}
+
+#[tokio::test]
+async fn a_destroyed_person_rejects_fencing_and_writes_with_not_found() {
+ let harness = start_fence_harness(
+ CachedPerson {
+ is_deleted: true,
+ ..test_cached_person()
+ },
+ None,
+ )
+ .await;
+ let mut client = harness.client.clone();
+ let team_id = harness.team_id;
+ let op = Uuid::now_v7();
+
+ let status = client
+ .fence_person(with_partition(
+ fence_request(team_id, harness.person_id, &op),
+ harness.partition,
+ ))
+ .await
+ .expect_err("cannot fence a destroyed person");
+ assert_eq!(status.code(), Code::NotFound);
+
+ let status = client
+ .update_person_properties(with_partition(
+ update_request(team_id, harness.person_id),
+ harness.partition,
+ ))
+ .await
+ .expect_err("cannot write to a destroyed person");
+ assert_eq!(status.code(), Code::NotFound);
+
+ let status = client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id,
+ person_id: harness.person_id,
+ read_options: None,
+ },
+ harness.partition,
+ ))
+ .await
+ .expect_err("a destroyed person reads as not-found");
+ assert_eq!(status.code(), Code::NotFound);
+}
+
+/// The takeover scan: a leader acquiring a partition rebuilds its fence map
+/// from the live marks in Postgres, keeping only its partition's rows and
+/// excluding merge targets (claimed, never fenced). Release drops exactly
+/// the partition's entries. Runs against the real persons DB.
+#[tokio::test]
+async fn the_takeover_scan_rebuilds_exactly_the_partitions_live_fences() {
+ use personhog_leader::fence::{drop_partition_fences, rebuild_partition_fences, FenceMap};
+
+ let pool = common::create_persons_pool().await;
+ let team_id = unique_team_id();
+ let op_id = Uuid::now_v7();
+
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'merge', $2, 'claimed', '{}'::jsonb)",
+ )
+ .bind(op_id)
+ .bind(team_id as i32)
+ .execute(&pool)
+ .await
+ .expect("insert op");
+
+ // Two live marks on different partitions, one merge target, one
+ // already-settled row: only the live non-target marks are fences.
+ let fenced_a: i64 = 1; // some partition
+ let mut fenced_b: i64 = 2;
+ while partition_for_person(team_id, fenced_b, NUM_PARTITIONS)
+ == partition_for_person(team_id, fenced_a, NUM_PARTITIONS)
+ {
+ fenced_b += 1;
+ }
+ let target: i64 = 100;
+ let settled: i64 = 101;
+ for (person_id, role, status) in [
+ (fenced_a, "source", "marked"),
+ (fenced_b, "victim", "sealed"),
+ (target, "target", "marked"),
+ (settled, "victim", "deleted"),
+ ] {
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), $4, $5)",
+ )
+ .bind(op_id)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .bind(role)
+ .bind(status)
+ .execute(&pool)
+ .await
+ .expect("insert mark");
+ }
+
+ let partition_a = partition_for_person(team_id, fenced_a, NUM_PARTITIONS);
+ let fences: FenceMap = Arc::new(DashMap::new());
+ let installed = rebuild_partition_fences(&pool, &fences, partition_a, NUM_PARTITIONS)
+ .await
+ .expect("scan runs");
+
+ let key = |person_id| personhog_leader::cache::PersonCacheKey { team_id, person_id };
+ assert!(installed >= 1, "the partition's live mark was installed");
+ let entry = fences
+ .get(&key(fenced_a))
+ .expect("live mark became a fence");
+ assert_eq!(entry.op_id, op_id);
+ drop(entry);
+ assert!(
+ fences.get(&key(fenced_b)).is_none(),
+ "another partition's mark is not ours"
+ );
+ assert!(
+ fences.get(&key(target)).is_none(),
+ "merge targets are claimed, never fenced"
+ );
+ assert!(
+ fences.get(&key(settled)).is_none(),
+ "settled rows are outside the mark set"
+ );
+
+ // A re-warm converges on the marks rather than accumulating: an entry
+ // a previous warm left behind for a person no longer marked is gone.
+ // (A handoff cancelled after warming, then re-acquired, takes this
+ // path — nothing else would ever clear that entry.)
+ let ghost = fenced_a + 1_000_000;
+ let ghost_partition = partition_for_person(team_id, ghost, NUM_PARTITIONS);
+ fences.insert(
+ key(ghost),
+ personhog_leader::fence::FenceState {
+ op_id: Uuid::now_v7(),
+ op_type: personhog_proto::personhog::types::v1::LifecycleOpType::Delete,
+ },
+ );
+ let reinstalled = rebuild_partition_fences(&pool, &fences, ghost_partition, NUM_PARTITIONS)
+ .await
+ .expect("re-warm runs");
+ assert!(
+ fences.get(&key(ghost)).is_none(),
+ "a re-warm drops entries the marks no longer justify"
+ );
+ if ghost_partition == partition_a {
+ assert_eq!(
+ reinstalled, installed,
+ "re-warming the same partition installs the same set"
+ );
+ }
+
+ let dropped = drop_partition_fences(&fences, partition_a, NUM_PARTITIONS);
+ assert!(dropped >= 1);
+ assert!(
+ fences.get(&key(fenced_a)).is_none(),
+ "release drops the partition's fences"
+ );
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .execute(&pool)
+ .await
+ .expect("cleanup");
+}
+
+/// The fence map's memory fuse: at capacity, a new fence sheds with
+/// RESOURCE_EXHAUSTED (backpressure the saga retries), while a re-seal of
+/// an already-fenced person still succeeds — refusing it would free
+/// nothing.
+#[tokio::test]
+async fn at_capacity_new_fences_shed_but_reseals_succeed() {
+ use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeader;
+
+ let team_id = unique_team_id();
+ let cache = Arc::new(PartitionedCache::new(1 << 20));
+ let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer.clone(),
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(InflightTracker::new()),
+ NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(&_mock_cluster.bootstrap_servers()),
+ PropertySizeLimits::new(655360, 524288),
+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
+ None,
+ None,
+ Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
+ )
+ .with_fence_capacity(1);
+
+ let (first_id, second_id) = (5000, 5001);
+ for id in [first_id, second_id] {
+ let partition = partition_for_person(team_id, id, NUM_PARTITIONS);
+ if !cache.has_partition(partition) {
+ cache.create_partition(partition);
+ }
+ seed_person(
+ &cache,
+ partition,
+ CachedPerson {
+ id,
+ team_id,
+ ..test_cached_person()
+ },
+ );
+ }
+ let (first_op, second_op) = (Uuid::now_v7(), Uuid::now_v7());
+
+ let fence = |person_id: i64, op: Uuid| {
+ let partition = partition_for_person(team_id, person_id, NUM_PARTITIONS);
+ with_partition(fence_request(team_id, person_id, &op), partition)
+ };
+
+ service
+ .fence_person(fence(first_id, first_op))
+ .await
+ .expect("the first fence fits");
+
+ let status = service
+ .fence_person(fence(second_id, second_op))
+ .await
+ .expect_err("a new fence past the cap must shed");
+ assert_eq!(status.code(), Code::ResourceExhausted);
+
+ service
+ .fence_person(fence(first_id, first_op))
+ .await
+ .expect("a re-seal of an already-fenced person is exempt from the cap");
+}
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index cc596700e5d0..44cf7d21248c 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -188,6 +188,7 @@ async fn unowned_partition_returns_failed_precondition() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -271,6 +272,7 @@ async fn missing_partition_metadata_returns_invalid_argument() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -357,6 +359,7 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -449,6 +452,7 @@ async fn writes_fenced_after_drain_reads_still_served() {
Arc::clone(&recovery),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -466,6 +470,9 @@ async fn writes_fenced_after_drain_reads_still_served() {
Arc::clone(&inflight),
Arc::clone(&dirty_index),
warming,
+ Arc::new(DashMap::new()),
+ None,
+ NUM_PARTITIONS,
pools,
None,
None,
@@ -575,6 +582,7 @@ async fn drain_fences_before_waiting_on_inflight() {
Arc::clone(&recovery),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -590,6 +598,9 @@ async fn drain_fences_before_waiting_on_inflight() {
Arc::clone(&inflight),
Arc::clone(&dirty_index),
warming,
+ Arc::new(DashMap::new()),
+ None,
+ NUM_PARTITIONS,
pools,
None,
None,
@@ -899,6 +910,7 @@ async fn update_produces_person_state_to_kafka() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -1014,6 +1026,7 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -1141,6 +1154,7 @@ async fn e2e_update_produces_to_local_kafka() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -1478,6 +1492,7 @@ async fn evicted_dirty_person_recovers_from_changelog() {
Arc::clone(&recovery),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -1581,6 +1596,7 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {
Arc::clone(&recovery),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -1690,6 +1706,7 @@ async fn writes_shed_when_dirty_index_is_full() {
test_recovery(&mock_cluster.bootstrap_servers()),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -1790,6 +1807,7 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {
Arc::clone(&recovery),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -1900,6 +1918,7 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {
Arc::clone(&recovery),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -2060,6 +2079,7 @@ async fn cancelled_recovery_returns_its_consumer_to_the_pool() {
is_identified: false,
is_user_id: None,
last_seen_at: None,
+ is_deleted: false,
};
let payload = person.encode_to_vec();
producer
@@ -2121,6 +2141,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {
"clickhouse_ingestion_warnings".to_string(),
WarningThrottle::new(DEFAULT_THROTTLE_PERIOD, NonZeroU32::new(2).unwrap()),
),
+ Arc::new(DashMap::new()),
None,
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -2572,6 +2593,7 @@ async fn an_unresolved_version_is_never_reused() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
Arc::clone(&emitted_versions),
@@ -2653,6 +2675,7 @@ async fn a_fenced_write_that_bounces_does_not_hand_its_version_back() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
Some(Arc::clone(&fenced)),
None,
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
@@ -2772,6 +2795,7 @@ async fn an_unknown_outcome_keeps_its_version(
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
Some(Arc::clone(&fenced)),
None,
Arc::clone(&emitted_versions),
@@ -2860,6 +2884,7 @@ async fn scalar_fields_merge_rather_than_assign() {
test_recovery(KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
None,
None,
Arc::clone(&emitted_versions),
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index 6e98228497e5..597162933522 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -37,6 +37,7 @@ fn make_person(team_id: i64, person_id: i64) -> Person {
is_identified: false,
is_user_id: None,
last_seen_at: None,
+ is_deleted: false,
}
}
@@ -375,6 +376,7 @@ async fn warming_fails_loudly_on_properties_json_error() {
is_identified: false,
is_user_id: None,
last_seen_at: None,
+ is_deleted: false,
};
produce_person_to_partition(&producer, 0, &bad).await;
diff --git a/rust/personhog-proto/src/lib.rs b/rust/personhog-proto/src/lib.rs
index 9331d677ac83..ca3e3673db1f 100644
--- a/rust/personhog-proto/src/lib.rs
+++ b/rust/personhog-proto/src/lib.rs
@@ -2,6 +2,32 @@ pub mod personhog {
pub mod types {
pub mod v1 {
tonic::include_proto!("personhog.types.v1");
+
+ impl LifecycleOpType {
+ /// The `lifecycle_op.op_type` value this variant mirrors —
+ /// also what the writer projects into the person tables'
+ /// `fencing_op_type` column.
+ pub const fn as_op_type_str(self) -> &'static str {
+ match self {
+ LifecycleOpType::Delete => "delete",
+ LifecycleOpType::Merge => "merge",
+ LifecycleOpType::Unspecified => "unspecified",
+ }
+ }
+
+ /// Inverse of [`as_op_type_str`]; unknown values map to
+ /// `Unspecified` (fail-open on the label only, never on the
+ /// fence itself — a fence's presence is its `op_id`).
+ ///
+ /// [`as_op_type_str`]: LifecycleOpType::as_op_type_str
+ pub fn from_op_type_str(op_type: &str) -> Self {
+ match op_type {
+ "delete" => LifecycleOpType::Delete,
+ "merge" => LifecycleOpType::Merge,
+ _ => LifecycleOpType::Unspecified,
+ }
+ }
+ }
}
}
pub mod identity {
diff --git a/rust/personhog-replica/src/service/field_mask.rs b/rust/personhog-replica/src/service/field_mask.rs
index e351f04fed57..ab73ece0331f 100644
--- a/rust/personhog-replica/src/service/field_mask.rs
+++ b/rust/personhog-replica/src/service/field_mask.rs
@@ -220,6 +220,7 @@ mod tests {
is_identified: true,
is_user_id: Some(false),
last_seen_at: Some(9999),
+ is_deleted: false,
}
}
diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rs
index 3d1d7407a2cb..91ea94c96c3a 100644
--- a/rust/personhog-router/src/proxy.rs
+++ b/rust/personhog-router/src/proxy.rs
@@ -38,6 +38,7 @@ pub const KNOWN_METHODS: &[&str] = &[
"DeletePersonlessDistinctIdsBatchForTeam",
"DeletePersons",
"DeletePersonsBatchForTeam",
+ "FencePerson",
"GetDistinctIdsForPerson",
"GetDistinctIdsForPersons",
"GetGroup",
@@ -59,6 +60,7 @@ pub const KNOWN_METHODS: &[&str] = &[
"InsertCohortMembers",
"ListCohortMemberIds",
"ListGroups",
+ "ReleaseFence",
"SetPersonDistinctIdVersionFloor",
"SetPersonVersionFloor",
"SplitPerson",
@@ -161,6 +163,16 @@ impl RawProxyInner {
.await;
(resp, "leader", call_ms)
}
+ // Lifecycle fence RPCs: person writes, so they route to the
+ // owning leader and share the handoff stash discipline.
+ "FencePerson" => {
+ let (resp, call_ms) = self.raw_proxy_to_leader(req, "FencePerson").await;
+ (resp, "leader", call_ms)
+ }
+ "ReleaseFence" => {
+ let (resp, call_ms) = self.raw_proxy_to_leader(req, "ReleaseFence").await;
+ (resp, "leader", call_ms)
+ }
"GetPerson" => {
let is_strong = req
.headers()
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index ed84e5892c14..2dca30a133d4 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -633,6 +633,7 @@ pub fn create_test_person() -> Person {
is_identified: true,
is_user_id: None,
last_seen_at: None,
+ is_deleted: false,
}
}
@@ -695,6 +696,22 @@ fn require_partition_metadata<T>(request: &Request<T>) -> Result<u32, Status> {
#[tonic::async_trait]
impl PersonHogLeader for TestLeaderService {
+ async fn fence_person(
+ &self,
+ request: Request<personhog_proto::personhog::types::v1::FencePersonRequest>,
+ ) -> Result<Response<personhog_proto::personhog::types::v1::FencePersonResponse>, Status> {
+ require_partition_metadata(&request)?;
+ Err(Status::unimplemented("not exercised by router tests"))
+ }
+
+ async fn release_fence(
+ &self,
+ request: Request<personhog_proto::personhog::types::v1::ReleaseFenceRequest>,
+ ) -> Result<Response<personhog_proto::personhog::types::v1::ReleaseFenceResponse>, Status> {
+ require_partition_metadata(&request)?;
+ Err(Status::unimplemented("not exercised by router tests"))
+ }
+
async fn get_person(
&self,
request: Request<GetPersonRequest>,
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index 1bd2f17c2e23..6a27b360894c 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -108,6 +108,19 @@ target/debug/personhog-test-harness gate --leaders 3 --routers 3 --duration 20s
# fires on the first handoff observed after the shutdown/scale-up)
target/debug/personhog-test-harness gate --leaders 3 --duration 20s \
--shutdown-after 5s --kill-handoff-target
+
+# Lifecycle fence window: fence 5 persons (delete-op) at 3s, release
+# (aborted) at 12s. While fenced, any write acked above the sealed version
+# is a violation — writes to fenced persons must be rejected, not lost.
+target/debug/personhog-test-harness gate --duration 15s \
+ --fence-after 3s --fence-release-after 12s
+
+# The fence durability property: the fence is part of the person document,
+# so it must survive a leader crash-restart (recovered via warming /
+# changelog recovery) — a fence that fails open after the restart acks a
+# write above the seal and fails the gate
+target/debug/personhog-test-harness gate --leaders 3 --duration 18s \
+ --fence-after 3s --restart-after 6s --fence-release-after 14s
```
### Known defects these scenarios reproduce
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index 1bb351f1e534..c6178dd5529d 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -222,6 +222,24 @@ pub struct GateArgs {
#[arg(long, default_value = "8s", value_parser = humantime::parse_duration)]
pub zombie_duration: Duration,
+ /// Fence the first --fence-count seeded persons (delete-op lifecycle
+ /// fence via the router) this long into the traffic phase. While
+ /// fenced, any write acked above the sealed version is a violation —
+ /// this is what catches a fence failing open across a leader crash or
+ /// handoff (compose with --restart-after / --kill-after between fence
+ /// and release). Requires --fence-release-after.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub fence_after: Option<Duration>,
+
+ /// Release the fences (aborted outcome — the persons resume life) this
+ /// long into the traffic phase. Must be after --fence-after.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub fence_release_after: Option<Duration>,
+
+ /// How many seeded persons the fence window covers.
+ #[arg(long, default_value_t = 5)]
+ pub fence_count: usize,
+
/// Crash-restart the writer this long into the traffic phase
/// (validates at-least-once redelivery under the version guard).
#[arg(long, value_parser = humantime::parse_duration)]
diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rs
index 61c887cb52dd..841ad55a2966 100644
--- a/rust/personhog-test-harness/src/client.rs
+++ b/rust/personhog-test-harness/src/client.rs
@@ -8,7 +8,9 @@ use personhog_proto::personhog::{
GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest,
},
types::v1::{
- ConsistencyLevel, Person, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
+ ConsistencyLevel, FencePersonRequest, FencePersonResponse, LifecycleOpType, Person,
+ ReleaseFenceRequest, ReleaseOutcome, UpdatePersonPropertiesRequest,
+ UpdatePersonPropertiesResponse,
},
};
use tonic::transport::Channel;
@@ -41,6 +43,46 @@ impl HarnessClient {
.context("GetPerson failed")
}
+ /// Fence a person for a delete op, returning the sealed version.
+ pub async fn fence_person(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ op_id: &uuid::Uuid,
+ ) -> Result<FencePersonResponse> {
+ self.inner
+ .fence_person(FencePersonRequest {
+ team_id,
+ person_id,
+ op_id: op_id.to_string(),
+ op_type: LifecycleOpType::Delete.into(),
+ })
+ .await
+ .context("FencePerson failed")
+ }
+
+ /// Release a fence with the aborted outcome: the person resumes life.
+ pub async fn release_fence_aborted(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ op_id: &uuid::Uuid,
+ ) -> Result<()> {
+ self.inner
+ .release_fence(ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid: String::new(),
+ op_id: op_id.to_string(),
+ outcome: ReleaseOutcome::Aborted.into(),
+ sealed_version: None,
+ created_at: 0,
+ })
+ .await
+ .context("ReleaseFence failed")?;
+ Ok(())
+ }
+
pub async fn update_properties(
&self,
team_id: i64,
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index 93dd4d3456d7..3dd2fe35a6bf 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -33,6 +33,8 @@ enum ChaosEvent {
WriterResume,
RouterKill { fast: bool },
RouterShutdown,
+ FencePersons,
+ ReleaseFences,
}
impl fmt::Display for ChaosEvent {
@@ -52,6 +54,8 @@ impl fmt::Display for ChaosEvent {
ChaosEvent::RouterKill { fast: false } => {
write!(f, "coordinator router crash (lease TTL expiry)")
}
+ ChaosEvent::FencePersons => write!(f, "fence persons (lifecycle delete op)"),
+ ChaosEvent::ReleaseFences => write!(f, "release fences (aborted)"),
ChaosEvent::RouterShutdown => write!(f, "coordinator router graceful shutdown"),
}
}
@@ -98,6 +102,14 @@ fn chaos_timeline(args: &GateArgs) -> Vec<(Duration, ChaosEvent)> {
if let Some(after) = args.router_shutdown_after {
events.push((after, ChaosEvent::RouterShutdown));
}
+ if let Some(after) = args.fence_after {
+ events.push((after, ChaosEvent::FencePersons));
+ events.push((
+ args.fence_release_after
+ .expect("validated: --fence-after requires --fence-release-after"),
+ ChaosEvent::ReleaseFences,
+ ));
+ }
events.sort_by_key(|(after, _)| *after);
events
}
@@ -127,7 +139,12 @@ fn default_bin_dir() -> PathBuf {
pub async fn run(args: GateArgs) -> Result<()> {
seed::validate_table_name(&args.pg_target_table)?;
let chaos = chaos_timeline(&args);
- if args.external_router_url.is_some() && (!chaos.is_empty() || args.kill_handoff_target) {
+ // Fence events act through the router client, so they are the one kind
+ // of chaos an external stack can host.
+ let needs_stack_chaos = chaos
+ .iter()
+ .any(|(_, event)| !matches!(event, ChaosEvent::FencePersons | ChaosEvent::ReleaseFences));
+ if args.external_router_url.is_some() && (needs_stack_chaos || args.kill_handoff_target) {
bail!("chaos flags require a spawned stack; they cannot target --external-router-url");
}
if args.external_router_url.is_some() && !args.leader_env.is_empty() {
@@ -157,6 +174,18 @@ pub async fn run(args: GateArgs) -> Result<()> {
if args.kill_handoff_target && args.shutdown_after.is_none() && args.scale_up_after.is_none() {
bail!("--kill-handoff-target needs a handoff-creating event (--shutdown-after or --scale-up-after)");
}
+ match (args.fence_after, args.fence_release_after) {
+ (Some(fence), Some(release)) if release <= fence => {
+ bail!("--fence-release-after must be after --fence-after");
+ }
+ (Some(_), None) | (None, Some(_)) => {
+ bail!("--fence-after and --fence-release-after must be given together");
+ }
+ _ => {}
+ }
+ if args.fence_after.is_some() && args.fence_count == 0 {
+ bail!("--fence-count must be at least 1 with --fence-after");
+ }
let mut stack = match &args.external_router_url {
Some(_) => None,
@@ -196,8 +225,15 @@ pub async fn run(args: GateArgs) -> Result<()> {
.context("connecting to persons DB")?;
// A crashed prior run may have left rows behind; the team id belongs to
- // the harness, so start from a clean slate.
+ // the harness, so start from a clean slate. Lifecycle ops included: a
+ // leftover mark would make a later run's takeover scan install a stale
+ // fence for this team.
seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
+ sqlx::query("DELETE FROM lifecycle_op WHERE team_id = $1")
+ .bind(args.team_id as i32)
+ .execute(&pool)
+ .await
+ .context("cleaning lifecycle ops")?;
let state = PersonState::new();
// A spawned stack always uses its own identity service — the gate's
// assertions target that stack, so an external identity service pointed
@@ -283,9 +319,113 @@ pub async fn run(args: GateArgs) -> Result<()> {
// through the disruption must still be visible afterwards.
let traffic_start = Instant::now();
let mut handoff_kill_armed = args.kill_handoff_target;
+ // Fenced persons and their shared op id, filled by FencePersons and
+ // drained by ReleaseFences.
+ let fence_op = uuid::Uuid::new_v4();
+ let mut fenced_persons: Vec<i64> = Vec::new();
for (after, event) in chaos {
- let stack = stack.as_mut().expect("chaos requires a spawned stack");
tokio::time::sleep_until((traffic_start + after).into()).await;
+ // The fence events act through the router like any client; they
+ // need no spawned stack.
+ match event {
+ ChaosEvent::FencePersons => {
+ // The durable fence record is the mark, written before any
+ // seal — a leader taking partition ownership mid-window
+ // rebuilds its fences from these rows. Fencing without them
+ // would not survive a restart (the harness acts as the
+ // saga's mark step here).
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'started', '{}'::jsonb)",
+ )
+ .bind(fence_op)
+ .bind(args.team_id as i32)
+ .execute(&pool)
+ .await
+ .context("inserting fence op row")?;
+ for &person_id in person_ids.iter().take(args.fence_count) {
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person \
+ (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'marked')",
+ )
+ .bind(fence_op)
+ .bind(args.team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .context("inserting fence mark")?;
+ }
+ for &person_id in person_ids.iter().take(args.fence_count) {
+ match client
+ .fence_person(args.team_id, person_id, &fence_op)
+ .await
+ {
+ Ok(response) => {
+ let sealed = response
+ .sealed
+ .map(|person| person.version)
+ .unwrap_or_default();
+ state.open_fence(person_id, sealed).await;
+ fenced_persons.push(person_id);
+ }
+ // Chaos may legitimately fail the call (a partition
+ // mid-handoff); an unfenced person just isn't
+ // asserted on.
+ Err(e) => tracing::warn!(person_id, error = %e, "fence failed; skipping"),
+ }
+ }
+ println!(
+ "Chaos at {:.1}s: {event} → {} of {} fenced (op {fence_op})",
+ traffic_start.elapsed().as_secs_f64(),
+ fenced_persons.len(),
+ args.fence_count,
+ );
+ continue;
+ }
+ ChaosEvent::ReleaseFences => {
+ let mut released = 0usize;
+ for person_id in fenced_persons.drain(..) {
+ // Close the window before releasing so a write racing
+ // the release ack cannot be flagged as a phantom
+ // violation.
+ state.close_fence(person_id).await;
+ match client
+ .release_fence_aborted(args.team_id, person_id, &fence_op)
+ .await
+ {
+ Ok(()) => released += 1,
+ Err(e) => {
+ tracing::warn!(person_id, error = %e, "release failed; person stays fenced")
+ }
+ }
+ }
+ // The op is over: settle it so the marks leave the live
+ // set (an aborted op's marks must not fence anyone after
+ // release).
+ sqlx::query(
+ "UPDATE lifecycle_op_person SET status = 'skipped_conflict' WHERE op_id = $1",
+ )
+ .bind(fence_op)
+ .execute(&pool)
+ .await
+ .context("settling fence marks")?;
+ sqlx::query(
+ "UPDATE lifecycle_op SET step = 'aborted', completed_at = now() WHERE op_id = $1",
+ )
+ .bind(fence_op)
+ .execute(&pool)
+ .await
+ .context("completing fence op")?;
+ println!(
+ "Chaos at {:.1}s: {event} → {released} released",
+ traffic_start.elapsed().as_secs_f64(),
+ );
+ continue;
+ }
+ _ => {}
+ }
+ let stack = stack.as_mut().expect("chaos requires a spawned stack");
let creates_handoff = matches!(event, ChaosEvent::Shutdown | ChaosEvent::ScaleUp);
let pod = match event {
ChaosEvent::Kill { fast } => Some(stack.kill_leader(fast).await?),
@@ -308,6 +448,9 @@ pub async fn run(args: GateArgs) -> Result<()> {
}
ChaosEvent::RouterKill { fast } => Some(stack.kill_coordinator_router(fast).await?),
ChaosEvent::RouterShutdown => Some(stack.shutdown_coordinator_router().await?),
+ ChaosEvent::FencePersons | ChaosEvent::ReleaseFences => {
+ unreachable!("fence events are dispatched before the stack match")
+ }
};
println!(
"Chaos at {:.1}s: {event} → pod {} | {}",
diff --git a/rust/personhog-test-harness/src/state.rs b/rust/personhog-test-harness/src/state.rs
index abeee0107a90..f27656641814 100644
--- a/rust/personhog-test-harness/src/state.rs
+++ b/rust/personhog-test-harness/src/state.rs
@@ -18,6 +18,12 @@ pub struct PersonState {
#[derive(Default)]
struct Journal {
persons: HashMap<i64, ExpectedPerson>,
+ /// Persons currently frozen by a lifecycle fence, mapped to their
+ /// sealed version. While a person is here, no write above the sealed
+ /// version may be acked — the fence's whole guarantee. Writes acked at
+ /// or below the sealed version are pre-fence acks whose responses
+ /// landed late, not violations.
+ fenced: HashMap<i64, i64>,
/// Acks that broke an invariant at journaling time. The leader
/// serializes writes per person and bumps the version on every change,
/// so each version of a person is assigned to at most one acked write;
@@ -80,6 +86,38 @@ impl PersonState {
actual: serde_json::json!(version),
});
}
+ if let Some(&sealed) = journal.fenced.get(&person_id) {
+ // A fenced person must reject writes; an ack above the sealed
+ // version means the fence failed open (leader amnesia, a
+ // fail-open check, a lost fence record). Acks at or below the
+ // seal raced the fence and were processed before it.
+ if version > sealed {
+ journal.anomalies.push(ConsistencyViolation {
+ person_id,
+ key: "__acked_write_while_fenced".to_string(),
+ expected: serde_json::json!(format!("no acked version above seal {sealed}")),
+ actual: serde_json::json!(version),
+ });
+ }
+ }
+ }
+
+ /// Open a fence window: from now until `close_fence`, any write acked
+ /// above `sealed_version` is a violation. Call after the fence ack (the
+ /// sealed version is only known then).
+ pub async fn open_fence(&self, person_id: i64, sealed_version: i64) {
+ self.inner
+ .write()
+ .await
+ .fenced
+ .insert(person_id, sealed_version);
+ }
+
+ /// Close a fence window. Call *before* issuing the release so a write
+ /// racing the release's ack cannot be flagged as a phantom violation;
+ /// the coverage lost is only the release call's own duration.
+ pub async fn close_fence(&self, person_id: i64) {
+ self.inner.write().await.fenced.remove(&person_id);
}
/// Journal an ack whose response reported no change applied. The data
@@ -348,6 +386,38 @@ mod tests {
assert!(person.written_properties.contains_key("k2"));
}
+ #[tokio::test]
+ async fn acked_writes_above_the_seal_are_violations_only_while_fenced() {
+ let state = PersonState::new();
+
+ // Pre-fence ack: no window open, nothing flagged.
+ state.record_write(1, 4, props(&[("k1", "v1")])).await;
+
+ state.open_fence(1, 5).await;
+ // An ack at or below the seal raced the fence (processed before it).
+ state.record_write(1, 5, props(&[("k2", "v2")])).await;
+ assert!(state.take_anomalies().await.is_empty());
+ // An ack above the seal means the fence failed open.
+ state.record_write(1, 6, props(&[("k3", "v3")])).await;
+ assert_eq!(
+ violation_keys(state.take_anomalies().await),
+ vec!["__acked_write_while_fenced"]
+ );
+ // Another person is unaffected by this person's fence.
+ state.record_write(2, 100, props(&[("k", "v")])).await;
+ assert!(state.take_anomalies().await.is_empty());
+
+ state.close_fence(1).await;
+ // Post-release writes above the old seal are normal life again.
+ state.record_write(1, 7, props(&[("k4", "v4")])).await;
+ assert!(state.take_anomalies().await.is_empty());
+
+ // The flagged write stays journaled: it was acked, so end-of-run
+ // verification must still hold it visible.
+ let snapshot = state.snapshot().await;
+ assert!(snapshot[&1].written_properties.contains_key("k3"));
+ }
+
#[tokio::test]
async fn strong_read_below_max_acked_version_is_a_violation() {
let state = PersonState::new();
diff --git a/rust/personhog-writer/src/buffer.rs b/rust/personhog-writer/src/buffer.rs
index 53c0c5020863..be59c42ad7e6 100644
--- a/rust/personhog-writer/src/buffer.rs
+++ b/rust/personhog-writer/src/buffer.rs
@@ -89,6 +89,7 @@ mod tests {
is_identified: false,
is_user_id: None,
last_seen_at: None,
+ is_deleted: false,
}
}
diff --git a/rust/personhog-writer/src/pg.rs b/rust/personhog-writer/src/pg.rs
index 24c17a7a3e76..f6aff7d37089 100644
--- a/rust/personhog-writer/src/pg.rs
+++ b/rust/personhog-writer/src/pg.rs
@@ -55,17 +55,19 @@ impl PgStore {
"INSERT INTO {table} (
id, team_id, uuid, properties, properties_last_updated_at,
properties_last_operation, created_at, version, is_identified,
- last_seen_at
+ last_seen_at, is_deleted
)
SELECT id, team_id, uuid, properties::jsonb,
properties_last_updated_at::jsonb, properties_last_operation::jsonb,
- created_at, version, is_identified, last_seen_at
+ created_at, version, is_identified, last_seen_at, is_deleted
FROM UNNEST(
$1::bigint[], $2::int[], $3::uuid[],
$4::text[], $5::text[], $6::text[],
- $7::timestamptz[], $8::bigint[], $9::bool[], $10::timestamptz[]
+ $7::timestamptz[], $8::bigint[], $9::bool[], $10::timestamptz[],
+ $11::bool[]
) AS u(id, team_id, uuid, properties, properties_last_updated_at,
- properties_last_operation, created_at, version, is_identified, last_seen_at)
+ properties_last_operation, created_at, version, is_identified, last_seen_at,
+ is_deleted)
ON CONFLICT (team_id, id) DO UPDATE SET
uuid = EXCLUDED.uuid,
properties = EXCLUDED.properties,
@@ -76,7 +78,8 @@ impl PgStore {
created_at = EXCLUDED.created_at,
version = EXCLUDED.version,
is_identified = EXCLUDED.is_identified,
- last_seen_at = GREATEST(EXCLUDED.last_seen_at, {table}.last_seen_at)
+ last_seen_at = GREATEST(EXCLUDED.last_seen_at, {table}.last_seen_at),
+ is_deleted = EXCLUDED.is_deleted
WHERE EXCLUDED.version > COALESCE({table}.version, -1)",
table = table_name
);
@@ -154,6 +157,7 @@ fn push_person<'a>(arrays: &mut PreparedArrays<'a>, p: &'a Person) -> Result<(),
Some(p.version),
p.is_identified,
last_seen_at,
+ p.is_deleted,
);
Ok(())
}
@@ -180,6 +184,7 @@ async fn run_upsert(
.bind(&arrays.versions)
.bind(&arrays.is_identified)
.bind(&arrays.last_seen_at)
+ .bind(&arrays.is_deleted)
.execute(pool)
.await
{
@@ -254,6 +259,7 @@ struct PreparedArrays<'a> {
versions: Vec<Option<i64>>,
is_identified: Vec<bool>,
last_seen_at: Vec<Option<DateTime<Utc>>>,
+ is_deleted: Vec<bool>,
}
impl<'a> PreparedArrays<'a> {
@@ -269,6 +275,7 @@ impl<'a> PreparedArrays<'a> {
versions: Vec::with_capacity(cap),
is_identified: Vec::with_capacity(cap),
last_seen_at: Vec::with_capacity(cap),
+ is_deleted: Vec::with_capacity(cap),
}
}
@@ -285,6 +292,7 @@ impl<'a> PreparedArrays<'a> {
version: Option<i64>,
is_identified: bool,
last_seen_at: Option<DateTime<Utc>>,
+ is_deleted: bool,
) {
self.ids.push(id);
self.team_ids.push(team_id);
@@ -298,6 +306,7 @@ impl<'a> PreparedArrays<'a> {
self.versions.push(version);
self.is_identified.push(is_identified);
self.last_seen_at.push(last_seen_at);
+ self.is_deleted.push(is_deleted);
}
}
diff --git a/rust/personhog-writer/tests/common/mod.rs b/rust/personhog-writer/tests/common/mod.rs
index 59649fed44ee..0aa9fd9ea889 100644
--- a/rust/personhog-writer/tests/common/mod.rs
+++ b/rust/personhog-writer/tests/common/mod.rs
@@ -103,9 +103,22 @@ pub fn make_person(team_id: i64, person_id: i64, version: i64) -> Person {
is_identified: false,
is_user_id: None,
last_seen_at: None,
+ is_deleted: false,
}
}
+/// A team id no other test shares, however the tests are scheduled.
+/// Random rather than counter- or clock-derived: nextest runs each test
+/// in its own process, so any per-process counter or seconds-based salt
+/// hands the same id to tests launched in the same second. Rows in the
+/// shared table are keyed by team, so a unique team makes concurrent
+/// tests collision-free: one test's cleanup can never delete another's
+/// rows. Stays inside the team_id column's range.
+#[allow(dead_code)]
+pub fn unique_team_id() -> i32 {
+ (uuid::Uuid::new_v4().as_u128() % 900_000_000 + 100_000_000) as i32
+}
+
/// Clean up test data from the personhog_person_tmp table for a given team.
pub async fn cleanup_team(pool: &PgPool, team_id: i32) {
sqlx::query("DELETE FROM personhog_person_tmp WHERE team_id = $1")
diff --git a/rust/personhog-writer/tests/integration.rs b/rust/personhog-writer/tests/integration.rs
index 7f7a19ecb8d5..ccc9910e8251 100644
--- a/rust/personhog-writer/tests/integration.rs
+++ b/rust/personhog-writer/tests/integration.rs
@@ -7,7 +7,7 @@ use std::time::Duration;
use chrono::{DateTime, Utc};
use common::{
cleanup_team, create_local_kafka_producer, create_mock_kafka, create_test_pool, make_person,
- KAFKA_BOOTSTRAP, TARGET_TABLE, TOPIC,
+ unique_team_id, KAFKA_BOOTSTRAP, TARGET_TABLE, TOPIC,
};
use personhog_proto::personhog::types::v1::Person;
use personhog_writer::consumer::{ConsumerTask, FlushBatch};
@@ -29,8 +29,7 @@ use tokio::sync::mpsc;
#[tokio::test]
async fn writer_upserts_person_to_pg() {
let pool = create_test_pool().await;
- let team_id: i32 = 99_001;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
@@ -60,10 +59,70 @@ async fn writer_upserts_person_to_pg() {
}
#[tokio::test]
-async fn writer_version_guard_skips_stale_updates() {
+async fn writer_projects_death_documents_as_tombstones() {
let pool = create_test_pool().await;
- let team_id: i32 = 99_002;
+ let team_id: i32 = unique_team_id();
+
+ let writer = PersonWriteStore::new(
+ PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
+ common::test_store_config(),
+ );
+
+ let fetch_row = |pool: sqlx::PgPool| async move {
+ let row: (i64, bool, String) = sqlx::query_as(
+ "SELECT version, is_deleted, properties::text \
+ FROM personhog_person_tmp WHERE team_id = $1 AND id = $2",
+ )
+ .bind(team_id)
+ .bind(1_i64)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ row
+ };
+
+ // Birth: live.
+ assert!(matches!(
+ writer
+ .upsert_batch(vec![make_person(team_id as i64, 1, 1)])
+ .await,
+ BatchOutcome::Success
+ ));
+ let row = fetch_row(pool.clone()).await;
+ assert!(!row.1);
+
+ // The death document projects as an ordinary update whose tombstone
+ // lands on the row: is_deleted set, properties scrubbed — never a row
+ // delete (burial is the GC job's, after ClickHouse erasure).
+ let mut death = make_person(team_id as i64, 1, 3);
+ death.is_deleted = true;
+ death.properties = b"{}".to_vec();
+ assert!(matches!(
+ writer.upsert_batch(vec![death]).await,
+ BatchOutcome::Success
+ ));
+ let row = fetch_row(pool.clone()).await;
+ assert_eq!(row.0, 3);
+ assert!(row.1, "the tombstone is projected, not a row delete");
+ assert_eq!(row.2, "{}");
+
+ // A lagging pre-death record must not resurrect the tombstone.
+ let stale = make_person(team_id as i64, 1, 2);
+ assert!(matches!(
+ writer.upsert_batch(vec![stale]).await,
+ BatchOutcome::Success
+ ));
+ let row = fetch_row(pool.clone()).await;
+ assert_eq!(row.0, 3, "version guard holds");
+ assert!(row.1, "the tombstone survives lagging writes");
+
cleanup_team(&pool, team_id).await;
+}
+
+#[tokio::test]
+async fn writer_version_guard_skips_stale_updates() {
+ let pool = create_test_pool().await;
+ let team_id: i32 = unique_team_id();
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
@@ -193,8 +252,7 @@ async fn writer_merges_meta_and_last_seen_instead_of_assigning() {
#[tokio::test]
async fn writer_upsert_batch_multiple_persons() {
let pool = create_test_pool().await;
- let team_id: i32 = 99_003;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
@@ -224,8 +282,7 @@ async fn writer_upsert_batch_multiple_persons() {
#[tokio::test]
async fn writer_surfaces_invalid_uuids_as_violations_never_silent_skips() {
let pool = create_test_pool().await;
- let team_id: i32 = 99_004;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
@@ -281,8 +338,7 @@ async fn writer_surfaces_invalid_uuids_as_violations_never_silent_skips() {
async fn consumer_flushes_on_buffer_size_threshold() {
let (mock_cluster, _producer) = create_mock_kafka().await;
let pool = create_test_pool().await;
- let team_id: i32 = 99_010;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let (flush_tx, flush_rx) = mpsc::channel::<FlushBatch>(2);
@@ -377,8 +433,7 @@ async fn consumer_flushes_on_buffer_size_threshold() {
async fn consumer_flushes_on_timer() {
let (mock_cluster, _producer) = create_mock_kafka().await;
let pool = create_test_pool().await;
- let team_id: i32 = 99_011;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let (flush_tx, flush_rx) = mpsc::channel::<FlushBatch>(2);
@@ -472,8 +527,7 @@ async fn consumer_flushes_on_timer() {
async fn consumer_deduplicates_multiple_updates_for_same_person() {
let (mock_cluster, _producer) = create_mock_kafka().await;
let pool = create_test_pool().await;
- let team_id: i32 = 99_012;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let (flush_tx, flush_rx) = mpsc::channel::<FlushBatch>(2);
@@ -701,8 +755,7 @@ async fn multi_lane_consumer_routes_partitions_and_flushes_independently() {
#[tokio::test]
async fn writer_processes_batch_from_channel() {
let pool = create_test_pool().await;
- let team_id: i32 = 99_020;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let (flush_tx, flush_rx) = mpsc::channel::<FlushBatch>(2);
@@ -1052,8 +1105,7 @@ async fn unapplyable_batch_halts_the_writer_before_any_later_batch() {
#[tokio::test]
async fn properties_size_violation_errors_and_writes_nothing() {
let pool = create_test_pool().await;
- let team_id: i32 = 99_050;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
let store = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
@@ -1099,8 +1151,7 @@ async fn properties_size_violation_errors_and_writes_nothing() {
#[tokio::test]
async fn e2e_produce_to_kafka_and_verify_pg_write() {
let pool = create_test_pool().await;
- let team_id: i32 = 99_030;
- cleanup_team(&pool, team_id).await;
+ let team_id: i32 = unique_team_id();
// Produce a Person proto to local Kafka
let producer = create_local_kafka_producer().await;
diff --git a/rust/property-defs-rs/tests/group_type_resolver.rs b/rust/property-defs-rs/tests/group_type_resolver.rs
index bda802e9b59e..efd1e66bc6d4 100644
--- a/rust/property-defs-rs/tests/group_type_resolver.rs
+++ b/rust/property-defs-rs/tests/group_type_resolver.rs
@@ -116,6 +116,20 @@ impl MockPersonHogService {
#[tonic::async_trait]
impl PersonHogService for MockPersonHogService {
+ async fn fence_person(
+ &self,
+ _req: Request<personhog_proto::personhog::types::v1::FencePersonRequest>,
+ ) -> Result<Response<personhog_proto::personhog::types::v1::FencePersonResponse>, Status> {
+ Err(Status::unimplemented("not exercised by this mock"))
+ }
+
+ async fn release_fence(
+ &self,
+ _req: Request<personhog_proto::personhog::types::v1::ReleaseFenceRequest>,
+ ) -> Result<Response<personhog_proto::personhog::types::v1::ReleaseFenceResponse>, Status> {
+ Err(Status::unimplemented("not exercised by this mock"))
+ }
+
async fn get_group_type_mappings_by_team_ids(
&self,
_req: Request<GetGroupTypeMappingsByTeamIdsRequest>,