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.

chore(personhog): leader path raw proxy (#68716)

Zach Brown467949c3ab04
diff --git a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts
index 334360320045..d88f213c5b7e 100644
--- a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts
+++ b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts
@@ -13,7 +13,7 @@ import { file_personhog_types_v1_common } from './common_pb'
export const file_personhog_types_v1_person: GenFile =
/*@__PURE__*/
fileDesc(
- 'Ch9wZXJzb25ob2cvdHlwZXMvdjEvcGVyc29uLnByb3RvEhJwZXJzb25ob2cudHlwZXMudjEingIKBlBlcnNvbhIKCgJpZBgBIAEoAxIMCgR1dWlkGAIgASgJEg8KB3RlYW1faWQYAyABKAMSEgoKcHJvcGVydGllcxgEIAEoDBIiChpwcm9wZXJ0aWVzX2xhc3RfdXBkYXRlZF9hdBgFIAEoDBIhChlwcm9wZXJ0aWVzX2xhc3Rfb3BlcmF0aW9uGAYgASgMEhIKCmNyZWF0ZWRfYXQYByABKAMSDwoHdmVyc2lvbhgIIAEoAxIVCg1pc19pZGVudGlmaWVkGAkgASgIEhcKCmlzX3VzZXJfaWQYCiABKAhIAIgBARIZCgxsYXN0X3NlZW5fYXQYCyABKANIAYgBAUINCgtfaXNfdXNlcl9pZEIPCg1fbGFzdF9zZWVuX2F0Ik4KFURpc3RpbmN0SWRXaXRoVmVyc2lvbhITCgtkaXN0aW5jdF9pZBgBIAEoCRIUCgd2ZXJzaW9uGAIgASgDSACIAQFCCgoIX3ZlcnNpb24iaAoVUGVyc29uV2l0aERpc3RpbmN0SWRzEhMKC2Rpc3RpbmN0X2lkGAEgASgJEi8KBnBlcnNvbhgCIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25IAIgBAUIJCgdfcGVyc29uImcKEVBlcnNvbkRpc3RpbmN0SWRzEhEKCXBlcnNvbl9pZBgBIAEoAxI/CgxkaXN0aW5jdF9pZHMYAiADKAsyKS5wZXJzb25ob2cudHlwZXMudjEuRGlzdGluY3RJZFdpdGhWZXJzaW9uIocBChhQZXJzb25XaXRoVGVhbURpc3RpbmN0SWQSLwoDa2V5GAEgASgLMiIucGVyc29uaG9nLnR5cGVzLnYxLlRlYW1EaXN0aW5jdElkEi8KBnBlcnNvbhgCIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25IAIgBAUIJCgdfcGVyc29uIm0KEEdldFBlcnNvblJlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxIRCglwZXJzb25faWQYAiABKAMSNQoMcmVhZF9vcHRpb25zGAMgASgLMh8ucGVyc29uaG9nLnR5cGVzLnYxLlJlYWRPcHRpb25zIk8KEUdldFBlcnNvblJlc3BvbnNlEi8KBnBlcnNvbhgBIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25IAIgBAUIJCgdfcGVyc29uIm8KEUdldFBlcnNvbnNSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEgoKcGVyc29uX2lkcxgCIAMoAxI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMiUwoPUGVyc29uc1Jlc3BvbnNlEisKB3BlcnNvbnMYASADKAsyGi5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uEhMKC21pc3NpbmdfaWRzGAIgAygDIm4KFkdldFBlcnNvbkJ5VXVpZFJlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxIMCgR1dWlkGAIgASgJEjUKDHJlYWRfb3B0aW9ucxgDIAEoCzIfLnBlcnNvbmhvZy50eXBlcy52MS5SZWFkT3B0aW9ucyJxChhHZXRQZXJzb25zQnlVdWlkc1JlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxINCgV1dWlkcxgCIAMoCRI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMiewocR2V0UGVyc29uQnlEaXN0aW5jdElkUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJEjUKDHJlYWRfb3B0aW9ucxgDIAEoCzIfLnBlcnNvbmhvZy50eXBlcy52MS5SZWFkT3B0aW9ucyKEAQokR2V0UGVyc29uc0J5RGlzdGluY3RJZHNJblRlYW1SZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSFAoMZGlzdGluY3RfaWRzGAIgAygJEjUKDHJlYWRfb3B0aW9ucxgDIAEoCzIfLnBlcnNvbmhvZy50eXBlcy52MS5SZWFkT3B0aW9ucyJgCiJQZXJzb25zQnlEaXN0aW5jdElkc0luVGVhbVJlc3BvbnNlEjoKB3Jlc3VsdHMYASADKAsyKS5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uV2l0aERpc3RpbmN0SWRzIpYBCh5HZXRQZXJzb25zQnlEaXN0aW5jdElkc1JlcXVlc3QSPQoRdGVhbV9kaXN0aW5jdF9pZHMYASADKAsyIi5wZXJzb25ob2cudHlwZXMudjEuVGVhbURpc3RpbmN0SWQSNQoMcmVhZF9vcHRpb25zGAIgASgLMh8ucGVyc29uaG9nLnR5cGVzLnYxLlJlYWRPcHRpb25zIl0KHFBlcnNvbnNCeURpc3RpbmN0SWRzUmVzcG9uc2USPQoHcmVzdWx0cxgBIAMoCzIsLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25XaXRoVGVhbURpc3RpbmN0SWQimQEKHkdldERpc3RpbmN0SWRzRm9yUGVyc29uUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhEKCXBlcnNvbl9pZBgCIAEoAxI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMSEgoFbGltaXQYBCABKANIAIgBAUIICgZfbGltaXQiYgofR2V0RGlzdGluY3RJZHNGb3JQZXJzb25SZXNwb25zZRI/CgxkaXN0aW5jdF9pZHMYASADKAsyKS5wZXJzb25ob2cudHlwZXMudjEuRGlzdGluY3RJZFdpdGhWZXJzaW9uIrEBCh9HZXREaXN0aW5jdElkc0ZvclBlcnNvbnNSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEgoKcGVyc29uX2lkcxgCIAMoAxI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMSHQoQbGltaXRfcGVyX3BlcnNvbhgEIAEoA0gAiAEBQhMKEV9saW1pdF9wZXJfcGVyc29uImYKIEdldERpc3RpbmN0SWRzRm9yUGVyc29uc1Jlc3BvbnNlEkIKE3BlcnNvbl9kaXN0aW5jdF9pZHMYASADKAsyJS5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uRGlzdGluY3RJZHMiuQEKHVVwZGF0ZVBlcnNvblByb3BlcnRpZXNSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEQoJcGVyc29uX2lkGAIgASgDEhIKCmV2ZW50X25hbWUYAyABKAkSFgoOc2V0X3Byb3BlcnRpZXMYBCABKAwSGwoTc2V0X29uY2VfcHJvcGVydGllcxgFIAEoDBIYChB1bnNldF9wcm9wZXJ0aWVzGAYgAygJEhEKCXBhcnRpdGlvbhgHIAEoDSJtCh5VcGRhdGVQZXJzb25Qcm9wZXJ0aWVzUmVzcG9uc2USLwoGcGVyc29uGAEgASgLMhoucGVyc29uaG9nLnR5cGVzLnYxLlBlcnNvbkgAiAEBEg8KB3VwZGF0ZWQYAiABKAhCCQoHX3BlcnNvbiI9ChREZWxldGVQZXJzb25zUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhQKDHBlcnNvbl91dWlkcxgCIAMoCSIuChVEZWxldGVQZXJzb25zUmVzcG9uc2USFQoNZGVsZXRlZF9jb3VudBgBIAEoAyJHCiBEZWxldGVQZXJzb25zQmF0Y2hGb3JUZWFtUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhIKCmJhdGNoX3NpemUYAiABKAMiOgohRGVsZXRlUGVyc29uc0JhdGNoRm9yVGVhbVJlc3BvbnNlEhUKDWRlbGV0ZWRfY291bnQYASABKAMiVwoSU3BsaXRQZXJzb25SZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEQoJcGVyc29uX2lkGAIgASgDEh0KFWRpc3RpbmN0X2lkc190b19zcGxpdBgDIAMoCSKOAQoLU3BsaXRSZXN1bHQSEwoLZGlzdGluY3RfaWQYASABKAkSFwoPbmV3X3BlcnNvbl91dWlkGAIgASgJEhoKEm5ld19wZXJzb25fdmVyc2lvbhgDIAEoAxITCgtwZGlfdmVyc2lvbhgEIAEoAxIgChhuZXdfcGVyc29uX2NyZWF0ZWRfYXRfbXMYBSABKAMiRgoTU3BsaXRQZXJzb25SZXNwb25zZRIvCgZzcGxpdHMYASADKAsyHy5wZXJzb25ob2cudHlwZXMudjEuU3BsaXRSZXN1bHRiBnByb3RvMw',
+ 'Ch9wZXJzb25ob2cvdHlwZXMvdjEvcGVyc29uLnByb3RvEhJwZXJzb25ob2cudHlwZXMudjEingIKBlBlcnNvbhIKCgJpZBgBIAEoAxIMCgR1dWlkGAIgASgJEg8KB3RlYW1faWQYAyABKAMSEgoKcHJvcGVydGllcxgEIAEoDBIiChpwcm9wZXJ0aWVzX2xhc3RfdXBkYXRlZF9hdBgFIAEoDBIhChlwcm9wZXJ0aWVzX2xhc3Rfb3BlcmF0aW9uGAYgASgMEhIKCmNyZWF0ZWRfYXQYByABKAMSDwoHdmVyc2lvbhgIIAEoAxIVCg1pc19pZGVudGlmaWVkGAkgASgIEhcKCmlzX3VzZXJfaWQYCiABKAhIAIgBARIZCgxsYXN0X3NlZW5fYXQYCyABKANIAYgBAUINCgtfaXNfdXNlcl9pZEIPCg1fbGFzdF9zZWVuX2F0Ik4KFURpc3RpbmN0SWRXaXRoVmVyc2lvbhITCgtkaXN0aW5jdF9pZBgBIAEoCRIUCgd2ZXJzaW9uGAIgASgDSACIAQFCCgoIX3ZlcnNpb24iaAoVUGVyc29uV2l0aERpc3RpbmN0SWRzEhMKC2Rpc3RpbmN0X2lkGAEgASgJEi8KBnBlcnNvbhgCIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25IAIgBAUIJCgdfcGVyc29uImcKEVBlcnNvbkRpc3RpbmN0SWRzEhEKCXBlcnNvbl9pZBgBIAEoAxI/CgxkaXN0aW5jdF9pZHMYAiADKAsyKS5wZXJzb25ob2cudHlwZXMudjEuRGlzdGluY3RJZFdpdGhWZXJzaW9uIocBChhQZXJzb25XaXRoVGVhbURpc3RpbmN0SWQSLwoDa2V5GAEgASgLMiIucGVyc29uaG9nLnR5cGVzLnYxLlRlYW1EaXN0aW5jdElkEi8KBnBlcnNvbhgCIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25IAIgBAUIJCgdfcGVyc29uIm0KEEdldFBlcnNvblJlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxIRCglwZXJzb25faWQYAiABKAMSNQoMcmVhZF9vcHRpb25zGAMgASgLMh8ucGVyc29uaG9nLnR5cGVzLnYxLlJlYWRPcHRpb25zIk8KEUdldFBlcnNvblJlc3BvbnNlEi8KBnBlcnNvbhgBIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25IAIgBAUIJCgdfcGVyc29uIm8KEUdldFBlcnNvbnNSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEgoKcGVyc29uX2lkcxgCIAMoAxI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMiUwoPUGVyc29uc1Jlc3BvbnNlEisKB3BlcnNvbnMYASADKAsyGi5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uEhMKC21pc3NpbmdfaWRzGAIgAygDIm4KFkdldFBlcnNvbkJ5VXVpZFJlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxIMCgR1dWlkGAIgASgJEjUKDHJlYWRfb3B0aW9ucxgDIAEoCzIfLnBlcnNvbmhvZy50eXBlcy52MS5SZWFkT3B0aW9ucyJxChhHZXRQZXJzb25zQnlVdWlkc1JlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxINCgV1dWlkcxgCIAMoCRI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMiewocR2V0UGVyc29uQnlEaXN0aW5jdElkUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJEjUKDHJlYWRfb3B0aW9ucxgDIAEoCzIfLnBlcnNvbmhvZy50eXBlcy52MS5SZWFkT3B0aW9ucyKEAQokR2V0UGVyc29uc0J5RGlzdGluY3RJZHNJblRlYW1SZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSFAoMZGlzdGluY3RfaWRzGAIgAygJEjUKDHJlYWRfb3B0aW9ucxgDIAEoCzIfLnBlcnNvbmhvZy50eXBlcy52MS5SZWFkT3B0aW9ucyJgCiJQZXJzb25zQnlEaXN0aW5jdElkc0luVGVhbVJlc3BvbnNlEjoKB3Jlc3VsdHMYASADKAsyKS5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uV2l0aERpc3RpbmN0SWRzIpYBCh5HZXRQZXJzb25zQnlEaXN0aW5jdElkc1JlcXVlc3QSPQoRdGVhbV9kaXN0aW5jdF9pZHMYASADKAsyIi5wZXJzb25ob2cudHlwZXMudjEuVGVhbURpc3RpbmN0SWQSNQoMcmVhZF9vcHRpb25zGAIgASgLMh8ucGVyc29uaG9nLnR5cGVzLnYxLlJlYWRPcHRpb25zIl0KHFBlcnNvbnNCeURpc3RpbmN0SWRzUmVzcG9uc2USPQoHcmVzdWx0cxgBIAMoCzIsLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25XaXRoVGVhbURpc3RpbmN0SWQimQEKHkdldERpc3RpbmN0SWRzRm9yUGVyc29uUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhEKCXBlcnNvbl9pZBgCIAEoAxI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMSEgoFbGltaXQYBCABKANIAIgBAUIICgZfbGltaXQiYgofR2V0RGlzdGluY3RJZHNGb3JQZXJzb25SZXNwb25zZRI/CgxkaXN0aW5jdF9pZHMYASADKAsyKS5wZXJzb25ob2cudHlwZXMudjEuRGlzdGluY3RJZFdpdGhWZXJzaW9uIrEBCh9HZXREaXN0aW5jdElkc0ZvclBlcnNvbnNSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEgoKcGVyc29uX2lkcxgCIAMoAxI1CgxyZWFkX29wdGlvbnMYAyABKAsyHy5wZXJzb25ob2cudHlwZXMudjEuUmVhZE9wdGlvbnMSHQoQbGltaXRfcGVyX3BlcnNvbhgEIAEoA0gAiAEBQhMKEV9saW1pdF9wZXJfcGVyc29uImYKIEdldERpc3RpbmN0SWRzRm9yUGVyc29uc1Jlc3BvbnNlEkIKE3BlcnNvbl9kaXN0aW5jdF9pZHMYASADKAsyJS5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uRGlzdGluY3RJZHMipgEKHVVwZGF0ZVBlcnNvblByb3BlcnRpZXNSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEQoJcGVyc29uX2lkGAIgASgDEhIKCmV2ZW50X25hbWUYAyABKAkSFgoOc2V0X3Byb3BlcnRpZXMYBCABKAwSGwoTc2V0X29uY2VfcHJvcGVydGllcxgFIAEoDBIYChB1bnNldF9wcm9wZXJ0aWVzGAYgAygJIm0KHlVwZGF0ZVBlcnNvblByb3BlcnRpZXNSZXNwb25zZRIvCgZwZXJzb24YASABKAsyGi5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uSACIAQESDwoHdXBkYXRlZBgCIAEoCEIJCgdfcGVyc29uIj0KFERlbGV0ZVBlcnNvbnNSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSFAoMcGVyc29uX3V1aWRzGAIgAygJIi4KFURlbGV0ZVBlcnNvbnNSZXNwb25zZRIVCg1kZWxldGVkX2NvdW50GAEgASgDIkcKIERlbGV0ZVBlcnNvbnNCYXRjaEZvclRlYW1SZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEgoKYmF0Y2hfc2l6ZRgCIAEoAyI6CiFEZWxldGVQZXJzb25zQmF0Y2hGb3JUZWFtUmVzcG9uc2USFQoNZGVsZXRlZF9jb3VudBgBIAEoAyJVCi5EZWxldGVQZXJzb25sZXNzRGlzdGluY3RJZHNCYXRjaEZvclRlYW1SZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEgoKYmF0Y2hfc2l6ZRgCIAEoAyJICi9EZWxldGVQZXJzb25sZXNzRGlzdGluY3RJZHNCYXRjaEZvclRlYW1SZXNwb25zZRIVCg1kZWxldGVkX2NvdW50GAEgASgDIlcKElNwbGl0UGVyc29uUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhEKCXBlcnNvbl9pZBgCIAEoAxIdChVkaXN0aW5jdF9pZHNfdG9fc3BsaXQYAyADKAkijgEKC1NwbGl0UmVzdWx0EhMKC2Rpc3RpbmN0X2lkGAEgASgJEhcKD25ld19wZXJzb25fdXVpZBgCIAEoCRIaChJuZXdfcGVyc29uX3ZlcnNpb24YAyABKAMSEwoLcGRpX3ZlcnNpb24YBCABKAMSIAoYbmV3X3BlcnNvbl9jcmVhdGVkX2F0X21zGAUgASgDIkYKE1NwbGl0UGVyc29uUmVzcG9uc2USLwoGc3BsaXRzGAEgAygLMh8ucGVyc29uaG9nLnR5cGVzLnYxLlNwbGl0UmVzdWx0ImMKJlNldFBlcnNvbkRpc3RpbmN0SWRWZXJzaW9uRmxvb3JSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEwoLZGlzdGluY3RfaWQYAiABKAkSEwoLbWluX3ZlcnNpb24YAyABKAMiZQonU2V0UGVyc29uRGlzdGluY3RJZFZlcnNpb25GbG9vclJlc3BvbnNlEi8KBnBlcnNvbhgBIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb25IAIgBAUIJCgdfcGVyc29uIlcKHFNldFBlcnNvblZlcnNpb25GbG9vclJlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxIRCglwZXJzb25faWQYAiABKAMSEwoLbWluX3ZlcnNpb24YAyABKAMiMAodU2V0UGVyc29uVmVyc2lvbkZsb29yUmVzcG9uc2USDwoHdXBkYXRlZBgBIAEoCGIGcHJvdG8z',
[file_personhog_types_v1_common]
)
@@ -615,15 +615,6 @@ export type UpdatePersonPropertiesRequest = Message<'personhog.types.v1.UpdatePe
* @generated from field: repeated string unset_properties = 6;
*/
unsetProperties: string[]
-
- /**
- * The partition this person belongs to, computed by the router via
- * murmur2(team_id:person_id) % num_partitions. The leader uses this
- * to look up the correct per-partition cache.
- *
- * @generated from field: uint32 partition = 7;
- */
- partition: number
}
/**
@@ -758,6 +749,57 @@ export const DeletePersonsBatchForTeamResponseSchema: GenMessage<DeletePersonsBa
/*@__PURE__*/
messageDesc(file_personhog_types_v1_person, 25)
+/**
+ * DeletePersonlessDistinctIdsBatchForTeamRequest deletes up to batch_size
+ * posthog_personlessdistinctid rows for a team. These rows have no person FK, so
+ * they aren't covered by person deletion. Callers should loop until deleted_count is 0.
+ *
+ * @generated from message personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamRequest
+ */
+export type DeletePersonlessDistinctIdsBatchForTeamRequest =
+ Message<'personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamRequest'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * Max rows to delete per call. Must be > 0 and <= 50000.
+ *
+ * @generated from field: int64 batch_size = 2;
+ */
+ batchSize: bigint
+ }
+
+/**
+ * Describes the message personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamRequest.
+ * Use `create(DeletePersonlessDistinctIdsBatchForTeamRequestSchema)` to create a new message.
+ */
+export const DeletePersonlessDistinctIdsBatchForTeamRequestSchema: GenMessage<DeletePersonlessDistinctIdsBatchForTeamRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_types_v1_person, 26)
+
+/**
+ * @generated from message personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamResponse
+ */
+export type DeletePersonlessDistinctIdsBatchForTeamResponse =
+ Message<'personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamResponse'> & {
+ /**
+ * Number of rows deleted. 0 means no more rows to delete.
+ *
+ * @generated from field: int64 deleted_count = 1;
+ */
+ deletedCount: bigint
+ }
+
+/**
+ * Describes the message personhog.types.v1.DeletePersonlessDistinctIdsBatchForTeamResponse.
+ * Use `create(DeletePersonlessDistinctIdsBatchForTeamResponseSchema)` to create a new message.
+ */
+export const DeletePersonlessDistinctIdsBatchForTeamResponseSchema: GenMessage<DeletePersonlessDistinctIdsBatchForTeamResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_types_v1_person, 27)
+
/**
* SplitPersonRequest splits specific distinct_ids off of a person onto new persons.
* Each distinct_id gets a new person with a deterministic UUID (UUIDv5 from team_id:distinct_id).
@@ -794,7 +836,7 @@ export type SplitPersonRequest = Message<'personhog.types.v1.SplitPersonRequest'
*/
export const SplitPersonRequestSchema: GenMessage<SplitPersonRequest> =
/*@__PURE__*/
- messageDesc(file_personhog_types_v1_person, 26)
+ messageDesc(file_personhog_types_v1_person, 28)
/**
* SplitResult describes a single distinct_id that was split onto a new person.
@@ -836,7 +878,7 @@ export type SplitResult = Message<'personhog.types.v1.SplitResult'> & {
* Describes the message personhog.types.v1.SplitResult.
* Use `create(SplitResultSchema)` to create a new message.
*/
-export const SplitResultSchema: GenMessage<SplitResult> = /*@__PURE__*/ messageDesc(file_personhog_types_v1_person, 27)
+export const SplitResultSchema: GenMessage<SplitResult> = /*@__PURE__*/ messageDesc(file_personhog_types_v1_person, 29)
/**
* @generated from message personhog.types.v1.SplitPersonResponse
@@ -856,4 +898,119 @@ export type SplitPersonResponse = Message<'personhog.types.v1.SplitPersonRespons
*/
export const SplitPersonResponseSchema: GenMessage<SplitPersonResponse> =
/*@__PURE__*/
- messageDesc(file_personhog_types_v1_person, 28)
+ messageDesc(file_personhog_types_v1_person, 30)
+
+/**
+ * SetPersonDistinctIdVersionFloorRequest bumps a person_distinct_id row's version.
+ * Used by the undelete repair flow to revive a soft-deleted distinct_id: raising the
+ * Postgres version keeps the plugin-server from later emitting a lower version that
+ * ClickHouse would ignore. The update is guarded so it never lowers a version: the row
+ * is updated only when its stored version is below min_version.
+ *
+ * @generated from message personhog.types.v1.SetPersonDistinctIdVersionFloorRequest
+ */
+export type SetPersonDistinctIdVersionFloorRequest =
+ Message<'personhog.types.v1.SetPersonDistinctIdVersionFloorRequest'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * @generated from field: string distinct_id = 2;
+ */
+ distinctId: string
+
+ /**
+ * Minimum version to set; applied only if the stored version is lower.
+ *
+ * @generated from field: int64 min_version = 3;
+ */
+ minVersion: bigint
+ }
+
+/**
+ * Describes the message personhog.types.v1.SetPersonDistinctIdVersionFloorRequest.
+ * Use `create(SetPersonDistinctIdVersionFloorRequestSchema)` to create a new message.
+ */
+export const SetPersonDistinctIdVersionFloorRequestSchema: GenMessage<SetPersonDistinctIdVersionFloorRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_types_v1_person, 31)
+
+/**
+ * @generated from message personhog.types.v1.SetPersonDistinctIdVersionFloorResponse
+ */
+export type SetPersonDistinctIdVersionFloorResponse =
+ Message<'personhog.types.v1.SetPersonDistinctIdVersionFloorResponse'> & {
+ /**
+ * The person the distinct_id maps to. Absent when the distinct_id does not exist
+ * (it has not been re-used yet). Present whenever the distinct_id exists, even if the
+ * guard left the version unchanged.
+ *
+ * @generated from field: optional personhog.types.v1.Person person = 1;
+ */
+ person?: Person
+ }
+
+/**
+ * Describes the message personhog.types.v1.SetPersonDistinctIdVersionFloorResponse.
+ * Use `create(SetPersonDistinctIdVersionFloorResponseSchema)` to create a new message.
+ */
+export const SetPersonDistinctIdVersionFloorResponseSchema: GenMessage<SetPersonDistinctIdVersionFloorResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_types_v1_person, 32)
+
+/**
+ * SetPersonVersionFloorRequest bumps a person's version. Used by the undelete repair
+ * flow to revive a soft-deleted person in ClickHouse. The update is guarded so it
+ * never lowers a version: the row is updated only when its stored version is below
+ * min_version.
+ *
+ * @generated from message personhog.types.v1.SetPersonVersionFloorRequest
+ */
+export type SetPersonVersionFloorRequest = Message<'personhog.types.v1.SetPersonVersionFloorRequest'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * @generated from field: int64 person_id = 2;
+ */
+ personId: bigint
+
+ /**
+ * Minimum version to set; applied only if the stored version is lower.
+ *
+ * @generated from field: int64 min_version = 3;
+ */
+ minVersion: bigint
+}
+
+/**
+ * Describes the message personhog.types.v1.SetPersonVersionFloorRequest.
+ * Use `create(SetPersonVersionFloorRequestSchema)` to create a new message.
+ */
+export const SetPersonVersionFloorRequestSchema: GenMessage<SetPersonVersionFloorRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_types_v1_person, 33)
+
+/**
+ * @generated from message personhog.types.v1.SetPersonVersionFloorResponse
+ */
+export type SetPersonVersionFloorResponse = Message<'personhog.types.v1.SetPersonVersionFloorResponse'> & {
+ /**
+ * True if a row was updated (the stored version was below min_version).
+ *
+ * @generated from field: bool updated = 1;
+ */
+ updated: boolean
+}
+
+/**
+ * Describes the message personhog.types.v1.SetPersonVersionFloorResponse.
+ * Use `create(SetPersonVersionFloorResponseSchema)` to create a new message.
+ */
+export const SetPersonVersionFloorResponseSchema: GenMessage<SetPersonVersionFloorResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_types_v1_person, 34)
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 6deac825af6f..38bcc2007c08 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,7 +15,7 @@ _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"\xb9\x01\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\x11\n\tpartition\x18\x07 \x01(\r"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"\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"\xa6\x01\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"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'
)
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
@@ -63,32 +63,32 @@ if not _descriptor._USE_C_DESCRIPTORS:
_globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_start = 2465
_globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_end = 2567
_globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_start = 2570
- _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_end = 2755
- _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_start = 2757
- _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_end = 2866
- _globals["_DELETEPERSONSREQUEST"]._serialized_start = 2868
- _globals["_DELETEPERSONSREQUEST"]._serialized_end = 2929
- _globals["_DELETEPERSONSRESPONSE"]._serialized_start = 2931
- _globals["_DELETEPERSONSRESPONSE"]._serialized_end = 2977
- _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_start = 2979
- _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_end = 3050
- _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_start = 3052
- _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_end = 3110
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_start = 3112
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_end = 3197
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_start = 3199
- _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_end = 3271
- _globals["_SPLITPERSONREQUEST"]._serialized_start = 3273
- _globals["_SPLITPERSONREQUEST"]._serialized_end = 3360
- _globals["_SPLITRESULT"]._serialized_start = 3363
- _globals["_SPLITRESULT"]._serialized_end = 3505
- _globals["_SPLITPERSONRESPONSE"]._serialized_start = 3507
- _globals["_SPLITPERSONRESPONSE"]._serialized_end = 3577
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_start = 3579
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_end = 3678
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_start = 3680
- _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_end = 3781
- _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_start = 3783
- _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_end = 3870
- _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_start = 3872
- _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_end = 3920
+ _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_end = 2736
+ _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_start = 2738
+ _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_end = 2847
+ _globals["_DELETEPERSONSREQUEST"]._serialized_start = 2849
+ _globals["_DELETEPERSONSREQUEST"]._serialized_end = 2910
+ _globals["_DELETEPERSONSRESPONSE"]._serialized_start = 2912
+ _globals["_DELETEPERSONSRESPONSE"]._serialized_end = 2958
+ _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_start = 2960
+ _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_end = 3031
+ _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_start = 3033
+ _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_end = 3091
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_start = 3093
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMREQUEST"]._serialized_end = 3178
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_start = 3180
+ _globals["_DELETEPERSONLESSDISTINCTIDSBATCHFORTEAMRESPONSE"]._serialized_end = 3252
+ _globals["_SPLITPERSONREQUEST"]._serialized_start = 3254
+ _globals["_SPLITPERSONREQUEST"]._serialized_end = 3341
+ _globals["_SPLITRESULT"]._serialized_start = 3344
+ _globals["_SPLITRESULT"]._serialized_end = 3486
+ _globals["_SPLITPERSONRESPONSE"]._serialized_start = 3488
+ _globals["_SPLITPERSONRESPONSE"]._serialized_end = 3558
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_start = 3560
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_end = 3659
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_start = 3661
+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_end = 3762
+ _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_start = 3764
+ _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_end = 3851
+ _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_start = 3853
+ _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_end = 3901
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 575ce0411bb0..138934f54a9d 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
@@ -313,29 +313,19 @@ class GetDistinctIdsForPersonsResponse(_message.Message):
) -> None: ...
class UpdatePersonPropertiesRequest(_message.Message):
- __slots__ = (
- "team_id",
- "person_id",
- "event_name",
- "set_properties",
- "set_once_properties",
- "unset_properties",
- "partition",
- )
+ __slots__ = ("team_id", "person_id", "event_name", "set_properties", "set_once_properties", "unset_properties")
TEAM_ID_FIELD_NUMBER: _ClassVar[int]
PERSON_ID_FIELD_NUMBER: _ClassVar[int]
EVENT_NAME_FIELD_NUMBER: _ClassVar[int]
SET_PROPERTIES_FIELD_NUMBER: _ClassVar[int]
SET_ONCE_PROPERTIES_FIELD_NUMBER: _ClassVar[int]
UNSET_PROPERTIES_FIELD_NUMBER: _ClassVar[int]
- PARTITION_FIELD_NUMBER: _ClassVar[int]
team_id: int
person_id: int
event_name: str
set_properties: bytes
set_once_properties: bytes
unset_properties: _containers.RepeatedScalarFieldContainer[str]
- partition: int
def __init__(
self,
@@ -345,7 +335,6 @@ class UpdatePersonPropertiesRequest(_message.Message):
set_properties: _Optional[bytes] = ...,
set_once_properties: _Optional[bytes] = ...,
unset_properties: _Optional[_Iterable[str]] = ...,
- partition: _Optional[int] = ...,
) -> None: ...
class UpdatePersonPropertiesResponse(_message.Message):
diff --git a/proto/personhog/leader/v1/leader.proto b/proto/personhog/leader/v1/leader.proto
index 69303a5eafd1..19ff78e2cf41 100644
--- a/proto/personhog/leader/v1/leader.proto
+++ b/proto/personhog/leader/v1/leader.proto
@@ -3,22 +3,17 @@ package personhog.leader.v1;
import "personhog/types/v1/person.proto";
-// Leader-specific get request that includes the partition for cache routing.
-message LeaderGetPersonRequest {
- int64 team_id = 1;
- int64 person_id = 2;
- // The partition this person belongs to, computed by the router.
- uint32 partition = 3;
-}
-
// PersonHogLeader is the internal write API exposed by leader pods.
// The router calls this service after hashing (team_id, person_id) to a
// partition and resolving the owning pod via the coordination routing table.
+// The partition travels in the `x-partition` request-metadata header, set by
+// the router, rather than in the request body — so the router can forward
+// client request bytes verbatim without a decode/re-encode.
service PersonHogLeader {
// Apply property updates to a person. Merges $set, $set_once, and $unset
// diffs into the cached person state.
rpc UpdatePersonProperties(personhog.types.v1.UpdatePersonPropertiesRequest) returns (personhog.types.v1.UpdatePersonPropertiesResponse);
// Strong consistency read: returns the latest person state from the leader's cache.
- rpc GetPerson(LeaderGetPersonRequest) returns (personhog.types.v1.GetPersonResponse);
+ rpc GetPerson(personhog.types.v1.GetPersonRequest) returns (personhog.types.v1.GetPersonResponse);
}
diff --git a/proto/personhog/types/v1/person.proto b/proto/personhog/types/v1/person.proto
index 3cc6e809a016..dea9bb032f4e 100644
--- a/proto/personhog/types/v1/person.proto
+++ b/proto/personhog/types/v1/person.proto
@@ -142,10 +142,6 @@ message UpdatePersonPropertiesRequest {
bytes set_once_properties = 5;
// Property keys to remove from the person.
repeated string unset_properties = 6;
- // The partition this person belongs to, computed by the router via
- // murmur2(team_id:person_id) % num_partitions. The leader uses this
- // to look up the correct per-partition cache.
- uint32 partition = 7;
}
message UpdatePersonPropertiesResponse {
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 852bc24a4b66..5c6a91d61e2d 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7427,6 +7427,7 @@ dependencies = [
"health",
"lifecycle",
"metrics",
+ "personhog-common",
"personhog-coordination",
"personhog-proto",
"prost 0.13.5",
@@ -11321,6 +11322,7 @@ dependencies = [
"axum 0.7.9",
"base64 0.22.1",
"bytes",
+ "flate2",
"h2 0.4.13",
"http 1.4.0",
"http-body 1.0.1",
@@ -11338,7 +11340,6 @@ dependencies = [
"tower-layer",
"tower-service",
"tracing",
- "zstd",
]
[[package]]
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 0abe1fc72c0b..6effcce51a3c 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -200,7 +200,13 @@ fancy-regex = "0.17"
lz-str = "0.2.1"
lz4 = "1.28"
opentelemetry-proto = { version = "0.29.0", features = ["with-serde"] }
-tonic = { version = "0.12.3", features = ["zstd"] }
+# gzip enables request decompression via accept_compressed. Response
+# compression stays with personhog-common's AsyncGzipLayer — never call
+# send_compressed: tonic's response-encoding negotiation matches any
+# compiled-in feature once the send set is non-empty, so a single
+# send_compressed(x) server would silently compress with whatever encoding
+# feature unification drags in.
+tonic = { version = "0.12.3", features = ["gzip"] }
tonic-build = "0.12"
clickhouse = { version = "0.13.2", features = [
"uuid",
diff --git a/rust/personhog-common/src/lib.rs b/rust/personhog-common/src/lib.rs
index 15d5f3b159cf..26ddf8c4e9c7 100644
--- a/rust/personhog-common/src/lib.rs
+++ b/rust/personhog-common/src/lib.rs
@@ -1,5 +1,6 @@
pub mod async_gzip;
pub mod grpc;
+pub mod partitioning;
mod pool_monitor;
pub use pool_monitor::{spawn_pool_monitor, MonitoredPool};
diff --git a/rust/personhog-common/src/partitioning.rs b/rust/personhog-common/src/partitioning.rs
new file mode 100644
index 000000000000..64c280e44d3d
--- /dev/null
+++ b/rust/personhog-common/src/partitioning.rs
@@ -0,0 +1,136 @@
+//! Person → changelog-partition mapping shared by the router (routing) and
+//! the leader (validation). Both sides must agree exactly: the router picks
+//! the partition a request is sent to, and the leader rejects requests whose
+//! `x-partition` doesn't match what it computes from the request body.
+
+/// Compute the Kafka partition for a person. The key is `team_id:person_id`,
+/// hashed with Kafka's default-partitioner murmur2 so partition placement
+/// matches messages produced with the same key by any standard Kafka client.
+pub fn partition_for_person(team_id: i64, person_id: i64, num_partitions: u32) -> u32 {
+ assert!(num_partitions > 0, "num_partitions must be > 0");
+ // i64 max string length is 20 chars. Two i64s + ':' = 41 bytes max.
+ let mut buf = [0u8; 41];
+ let len = {
+ use std::io::Write;
+ let mut cursor = std::io::Cursor::new(&mut buf[..]);
+ write!(cursor, "{team_id}:{person_id}").unwrap();
+ cursor.position() as usize
+ };
+ let hash = kafka_murmur2(&buf[..len]);
+ // Kafka's toPositive: hash & 0x7fffffff
+ let positive = (hash & 0x7fffffff) as u32;
+ positive % num_partitions
+}
+
+/// Kafka-compatible murmur2 hash.
+///
+/// This matches the Java Kafka client's `Utils.murmur2()` implementation
+/// so that partition assignment is consistent with Kafka's default partitioner.
+fn kafka_murmur2(data: &[u8]) -> i32 {
+ let length = data.len();
+ let seed: i32 = 0x9747b28cu32 as i32;
+ let m: i32 = 0x5bd1e995u32 as i32;
+ let r: u32 = 24;
+
+ let mut h: i32 = seed ^ (length as i32);
+
+ let length4 = length / 4;
+ for i in 0..length4 {
+ let i4 = i * 4;
+ let mut k: i32 = (data[i4] as i32 & 0xff)
+ | ((data[i4 + 1] as i32 & 0xff) << 8)
+ | ((data[i4 + 2] as i32 & 0xff) << 16)
+ | ((data[i4 + 3] as i32 & 0xff) << 24);
+
+ k = k.wrapping_mul(m);
+ k ^= (k as u32 >> r) as i32;
+ k = k.wrapping_mul(m);
+ h = h.wrapping_mul(m);
+ h ^= k;
+ }
+
+ let tail = length & !3;
+ match length % 4 {
+ 3 => {
+ h ^= (data[tail + 2] as i32 & 0xff) << 16;
+ h ^= (data[tail + 1] as i32 & 0xff) << 8;
+ h ^= data[tail] as i32 & 0xff;
+ h = h.wrapping_mul(m);
+ }
+ 2 => {
+ h ^= (data[tail + 1] as i32 & 0xff) << 8;
+ h ^= data[tail] as i32 & 0xff;
+ h = h.wrapping_mul(m);
+ }
+ 1 => {
+ h ^= data[tail] as i32 & 0xff;
+ h = h.wrapping_mul(m);
+ }
+ _ => {}
+ }
+
+ h ^= (h as u32 >> 13) as i32;
+ h = h.wrapping_mul(m);
+ h ^= (h as u32 >> 15) as i32;
+
+ h
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn murmur2_deterministic_and_consistent() {
+ // Same input always produces same hash
+ let h1 = kafka_murmur2(b"42");
+ let h2 = kafka_murmur2(b"42");
+ assert_eq!(h1, h2);
+
+ // Different inputs produce different hashes
+ let h3 = kafka_murmur2(b"43");
+ assert_ne!(h1, h3);
+ }
+
+ /// Pin murmur2 output so accidental algorithm changes are caught.
+ /// These values must match `org.apache.kafka.common.utils.Utils.murmur2()`
+ /// to ensure partition assignment is consistent with Kafka's default partitioner.
+ #[test]
+ fn murmur2_pinned_values() {
+ assert_eq!(kafka_murmur2(b""), 275646681);
+ assert_eq!(kafka_murmur2(b"21"), -973932308);
+ assert_eq!(kafka_murmur2(b"42"), 417700972);
+ assert_eq!(kafka_murmur2(b"1:42"), -1141388408);
+ assert_eq!(kafka_murmur2(b"hello"), 2132663229);
+ assert_eq!(kafka_murmur2(b"test-key"), -1341026247);
+ }
+
+ #[test]
+ fn partition_for_person_deterministic() {
+ let p1 = partition_for_person(1, 42, 16);
+ let p2 = partition_for_person(1, 42, 16);
+ assert_eq!(p1, p2);
+ assert!(p1 < 16);
+
+ // Different person_ids should (likely) produce different partitions
+ let p3 = partition_for_person(1, 43, 16);
+ assert!(p3 < 16);
+ }
+
+ #[test]
+ fn partition_distribution_is_reasonable() {
+ let mut counts = [0u32; 8];
+ for person_id in 1..=1000 {
+ let partition = partition_for_person(1, person_id, 8);
+ counts[partition as usize] += 1;
+ }
+
+ // Each partition should get at least some keys (rough check)
+ for (i, count) in counts.iter().enumerate() {
+ assert!(
+ *count > 50,
+ "partition {i} only got {count} keys out of 1000"
+ );
+ }
+ }
+}
diff --git a/rust/personhog-leader/Cargo.toml b/rust/personhog-leader/Cargo.toml
index 0a085f1f8077..f1a21d130222 100644
--- a/rust/personhog-leader/Cargo.toml
+++ b/rust/personhog-leader/Cargo.toml
@@ -6,6 +6,7 @@ publish = false
[dependencies]
personhog-proto = { path = "../personhog-proto" }
+personhog-common = { path = "../personhog-common" }
personhog-coordination = { path = "../personhog-coordination" }
assignment-coordination = { path = "../common/assignment-coordination" }
common-kafka = { path = "../common/kafka" }
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index a8ecbe86492b..68ea2e348421 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -16,6 +16,62 @@ pub struct Config {
#[envconfig(default = "9102")]
pub metrics_port: u16,
+ // ── gRPC server ──────────────────────────────────────────────
+ /// Interval between HTTP/2 keepalive pings sent by the gRPC server (0 = disabled)
+ #[envconfig(default = "30")]
+ pub grpc_keepalive_interval_secs: u64,
+
+ /// Timeout for a keepalive ping ack before considering the connection dead
+ #[envconfig(default = "10")]
+ pub grpc_keepalive_timeout_secs: u64,
+
+ /// Maximum gRPC message size to encode (send), in bytes. Defaults to 128 MiB.
+ #[envconfig(default = "134217728")]
+ pub grpc_max_send_message_size: usize,
+
+ /// Maximum gRPC message size to decode (receive), in bytes.
+ #[envconfig(default = "134217728")]
+ pub grpc_max_recv_message_size: usize,
+
+ /// Maximum age of a gRPC server connection before it is gracefully
+ /// closed (GOAWAY), guarding against half-dead long-lived connections.
+ /// 0 = disabled (connections live indefinitely).
+ #[envconfig(default = "300")]
+ pub grpc_max_connection_age_secs: u64,
+
+ /// Maximum concurrent in-flight gRPC requests before the server sheds
+ /// load with RESOURCE_EXHAUSTED so the router retries on another pod.
+ /// 0 = disabled.
+ #[envconfig(default = "0")]
+ pub max_concurrent_requests: usize,
+
+ // ── Response compression ─────────────────────────────────────
+ /// When true, gzip-compress responses for clients that advertise gzip
+ /// in `grpc-accept-encoding`. Compression runs on a blocking thread
+ /// pool instead of the tokio runtime.
+ #[envconfig(default = "false")]
+ pub gzip_response_compression: bool,
+
+ /// Gzip compression level (1–9). Lower is faster, higher compresses more.
+ #[envconfig(default = "6")]
+ pub gzip_compression_level: u32,
+
+ /// Minimum response payload size in bytes to compress. Payloads smaller
+ /// than this pass through uncompressed.
+ #[envconfig(default = "256")]
+ pub gzip_min_payload_size: usize,
+
+ /// Log a warning when a response exceeds this size in bytes, even
+ /// for uncompressed passthrough. 0 = disabled. Default 4 MiB.
+ #[envconfig(default = "4194304")]
+ pub gzip_max_response_size: usize,
+
+ /// When true, responses exceeding `gzip_max_response_size` are rejected
+ /// with RESOURCE_EXHAUSTED; when false, the oversized
+ /// response is delivered normally (monitor mode).
+ #[envconfig(default = "false")]
+ pub gzip_max_response_size_enforce: bool,
+
// ── Kafka durability ─────────────────────────────────────────
#[envconfig(nested = true)]
pub kafka: KafkaConfig,
@@ -102,6 +158,30 @@ pub struct Config {
}
impl Config {
+ pub fn grpc_keepalive_interval(&self) -> Option<Duration> {
+ if self.grpc_keepalive_interval_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.grpc_keepalive_interval_secs))
+ }
+ }
+
+ pub fn grpc_keepalive_timeout(&self) -> Option<Duration> {
+ if self.grpc_keepalive_timeout_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.grpc_keepalive_timeout_secs))
+ }
+ }
+
+ pub fn grpc_max_connection_age(&self) -> Option<Duration> {
+ if self.grpc_max_connection_age_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.grpc_max_connection_age_secs))
+ }
+ }
+
pub fn etcd_endpoint_list(&self) -> Vec<String> {
self.etcd_endpoints
.split(',')
diff --git a/rust/personhog-leader/src/kafka.rs b/rust/personhog-leader/src/kafka.rs
index 44562d8af0eb..a5d8a2edcc15 100644
--- a/rust/personhog-leader/src/kafka.rs
+++ b/rust/personhog-leader/src/kafka.rs
@@ -16,7 +16,15 @@ pub fn changelog_message_key(team_id: i64, person_id: i64) -> String {
/// Produce a person state changelog message to Kafka.
///
/// Encodes the `Person` proto as the message payload and uses
-/// `{team_id}:{person_id}` as the key for compaction and partitioning.
+/// `{team_id}:{person_id}` as the key for compaction. The message is
+/// produced to an explicit partition — the person's routing partition —
+/// rather than relying on the producer's key partitioner. Warming rebuilds
+/// one routing partition's cache by consuming the same-numbered Kafka
+/// partition, so the two numbering schemes must agree; producing explicitly
+/// makes that alignment structural instead of depending on the partitioner
+/// config matching the router's murmur2 (librdkafka's default partitioner
+/// is CRC32-based and routes keys differently). A partition-count mismatch
+/// fails loudly at produce time instead of silently mis-sharding.
/// Returns `Ok(())` on successful delivery, or an error string on failure.
///
/// The handoff protocol relies on "handler returned Ok == message durable in Kafka."
@@ -27,12 +35,16 @@ pub fn changelog_message_key(team_id: i64, person_id: i64) -> String {
pub async fn produce_person_changelog(
producer: &FutureProducer<KafkaContext>,
topic: &str,
+ partition: u32,
person: &Person,
) -> Result<(), String> {
let key = changelog_message_key(person.team_id, person.id);
let payload = person.encode_to_vec();
- let record = FutureRecord::to(topic).key(&key).payload(&payload);
+ let record = FutureRecord::to(topic)
+ .partition(partition as i32)
+ .key(&key)
+ .payload(&payload);
match producer.send_result(record) {
Ok(delivery_future) => match delivery_future.await {
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index b098c8c4a635..cc4c94f7b350 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -8,6 +8,8 @@ use common_metrics::setup_metrics_routes;
use dashmap::DashMap;
use envconfig::Envconfig;
use lifecycle::{ComponentOptions, Manager};
+use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};
+use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetricsLayer};
use personhog_coordination::pod::{PodConfig, PodHandle};
use personhog_coordination::store::PersonhogStore;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
@@ -137,6 +139,25 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)?)
};
+ // Connect to etcd for coordination and the partition count
+ let etcd_config = StoreConfig {
+ endpoints: config.etcd_endpoint_list(),
+ prefix: config.etcd_prefix.clone(),
+ };
+ let etcd_store = EtcdStore::connect(etcd_config)
+ .await
+ .expect("Failed to connect to etcd");
+ let store = Arc::new(PersonhogStore::new(etcd_store));
+
+ // Read total_partitions from etcd (set by kafka-assigner) — the same
+ // source the router hashes against, so partition validation can never
+ // drift between the two.
+ let num_partitions = store
+ .get_total_partitions()
+ .await
+ .expect("Failed to read total_partitions from etcd");
+ tracing::info!(num_partitions, "loaded partition count from etcd");
+
let locks = Arc::new(DashMap::new());
let inflight = Arc::new(personhog_leader::inflight::InflightTracker::new());
let service = PersonHogLeaderService::new(
@@ -146,18 +167,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
fallback_pool,
Arc::clone(&locks),
Arc::clone(&inflight),
+ num_partitions,
);
- // Connect to etcd and start coordination
- let etcd_config = StoreConfig {
- endpoints: config.etcd_endpoint_list(),
- prefix: config.etcd_prefix.clone(),
- };
- let etcd_store = EtcdStore::connect(etcd_config)
- .await
- .expect("Failed to connect to etcd");
- let store = Arc::new(PersonhogStore::new(etcd_store));
-
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
@@ -210,19 +222,77 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
});
- // gRPC server
+ // gRPC server. Mirrors the replica's middleware stack so the router's
+ // per-backend metrics (processing time, transport/network overhead) and
+ // response compression behave identically on both backends. No tonic
+ // codec compression: requests always arrive uncompressed (the router
+ // rejects compressed leader requests before forwarding — it scans the
+ // request bytes for the routing key), and response compression is
+ // exclusively the gzip layer.
let grpc_addr = config.grpc_address;
+ let keepalive_interval = config.grpc_keepalive_interval();
+ let keepalive_timeout = config.grpc_keepalive_timeout();
+ let max_connection_age = config.grpc_max_connection_age();
+ let max_send = config.grpc_max_send_message_size;
+ let max_recv = config.grpc_max_recv_message_size;
+ let max_concurrent_requests = config.max_concurrent_requests;
+ let max_response_size = if config.gzip_max_response_size > 0 {
+ Some(config.gzip_max_response_size)
+ } else {
+ None
+ };
+ let gzip_config = AsyncGzipConfig::new(
+ config.gzip_response_compression,
+ config.gzip_compression_level,
+ config.gzip_min_payload_size,
+ )
+ .with_max_response_size(max_response_size, config.gzip_max_response_size_enforce);
+
+ if gzip_config.enabled {
+ tracing::info!(
+ level = gzip_config.compression_level,
+ min_payload_size = gzip_config.min_payload_size,
+ "Async gzip response compression enabled"
+ );
+ }
+ if max_concurrent_requests > 0 {
+ tracing::info!(
+ limit = max_concurrent_requests,
+ "gRPC load shedding enabled"
+ );
+ }
tracing::info!("Starting gRPC server on {}", grpc_addr);
tokio::spawn(async move {
let _guard = grpc_handle.process_scope();
- if let Err(e) = Server::builder()
+ let listener = match tokio::net::TcpListener::bind(grpc_addr).await {
+ Ok(l) => l,
+ Err(e) => {
+ grpc_handle.signal_failure(format!("Failed to bind gRPC port: {e}"));
+ return;
+ }
+ };
+ let incoming = tracked_tcp_incoming(listener);
+ let mut server = Server::builder()
+ .http2_keepalive_interval(keepalive_interval)
+ .http2_keepalive_timeout(keepalive_timeout);
+ if let Some(age) = max_connection_age {
+ server = server.max_connection_age(age);
+ }
+ if let Err(e) = server
+ .layer(AsyncGzipLayer::new(gzip_config))
+ .layer(GrpcMetricsLayer::default().with_processing_time_header())
+ .layer(GrpcLoadShedLayer::new(max_concurrent_requests))
.add_service(
+ // accept_compressed only decodes gzip request frames from
+ // opted-in clients; responses stay with the AsyncGzipLayer
+ // (never send_compressed — see the tonic entry in Cargo.toml).
PersonHogLeaderServer::new(service)
- .accept_compressed(CompressionEncoding::Zstd)
- .send_compressed(CompressionEncoding::Zstd),
+ .accept_compressed(CompressionEncoding::Gzip)
+ .max_encoding_message_size(max_send)
+ .max_decoding_message_size(max_recv),
)
- .serve_with_shutdown(grpc_addr, grpc_handle.shutdown_signal())
+ .serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
.await
{
grpc_handle.signal_failure(format!("gRPC server error: {e}"));
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index eab44069a651..a51b35675e9e 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -4,15 +4,17 @@ use common_kafka::kafka_producer::KafkaContext;
use dashmap::DashMap;
use metrics::counter;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeader;
-use personhog_proto::personhog::leader::v1::LeaderGetPersonRequest;
use personhog_proto::personhog::types::v1::{
- GetPersonResponse, Person, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
+ GetPersonRequest, GetPersonResponse, Person, UpdatePersonPropertiesRequest,
+ UpdatePersonPropertiesResponse,
};
use rdkafka::producer::FutureProducer;
use sqlx::postgres::PgPool;
use tokio::sync::Mutex;
use tonic::{Request, Response, Status};
+use personhog_common::partitioning::partition_for_person;
+
use crate::cache::{CacheLookup, CachedPerson, PartitionedCache, PersonCacheKey};
use crate::inflight::InflightTracker;
use crate::kafka::produce_person_changelog;
@@ -31,6 +33,10 @@ pub struct PersonHogLeaderService {
fallback_pool: Option<PgPool>,
/// Per-partition inflight counter used to drive the handoff drain phase.
inflight: Arc<InflightTracker>,
+ /// Total changelog partition count, read from etcd at startup (the same
+ /// source the router uses). Used to validate the router's routing
+ /// decision against each request's key.
+ num_partitions: u32,
}
impl PersonHogLeaderService {
@@ -41,6 +47,7 @@ impl PersonHogLeaderService {
fallback_pool: Option<PgPool>,
locks: Arc<DashMap<PersonCacheKey, Arc<Mutex<()>>>>,
inflight: Arc<InflightTracker>,
+ num_partitions: u32,
) -> Self {
Self {
cache,
@@ -49,9 +56,34 @@ impl PersonHogLeaderService {
changelog_topic,
fallback_pool,
inflight,
+ num_partitions,
}
}
+ /// 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
+ /// routing-key headers or the hash implementations diverged; serving it
+ /// would read or write through the wrong partition's cache, so fail
+ /// closed.
+ #[allow(clippy::result_large_err)]
+ fn validate_partition(
+ &self,
+ partition: u32,
+ team_id: i64,
+ person_id: i64,
+ ) -> Result<(), Status> {
+ let expected = partition_for_person(team_id, person_id, self.num_partitions);
+ if partition != expected {
+ counter!("personhog_leader_partition_mismatch_total").increment(1);
+ return Err(Status::invalid_argument(format!(
+ "x-partition {partition} does not match partition {expected} \
+ derived from team_id={team_id} person_id={person_id}"
+ )));
+ }
+ Ok(())
+ }
+
/// Load a person from PG and populate the cache. Assumes the caller
/// holds the per-key lock.
async fn load_from_pg(
@@ -154,19 +186,40 @@ fn cached_person_to_proto(p: &CachedPerson) -> Person {
}
}
+/// Extract the routing partition from the `x-partition` request-metadata
+/// header. The router stamps this on every leader call after hashing
+/// `(team_id, person_id)`; its absence means a misrouted or malformed
+/// request, so we fail closed with `InvalidArgument` rather than guessing.
+// `Status` is the idiomatic tonic error throughout this service; the small
+// `Ok(u32)` against a large `Status` trips `result_large_err`, but boxing
+// here would diverge from every other handler's signature.
+#[allow(clippy::result_large_err)]
+fn partition_from_metadata<T>(request: &Request<T>) -> Result<u32, Status> {
+ request
+ .metadata()
+ .get("x-partition")
+ .ok_or_else(|| Status::invalid_argument("missing x-partition metadata"))?
+ .to_str()
+ .map_err(|_| Status::invalid_argument("x-partition metadata is not valid ASCII"))?
+ .parse::<u32>()
+ .map_err(|_| Status::invalid_argument("x-partition metadata is not a valid u32"))
+}
+
#[tonic::async_trait]
impl PersonHogLeader for PersonHogLeaderService {
async fn get_person(
&self,
- request: Request<LeaderGetPersonRequest>,
+ request: Request<GetPersonRequest>,
) -> Result<Response<GetPersonResponse>, Status> {
+ let partition = partition_from_metadata(&request)?;
let req = request.into_inner();
+ self.validate_partition(partition, req.team_id, req.person_id)?;
let cache_key = PersonCacheKey {
team_id: req.team_id,
person_id: req.person_id,
};
- let person = self.lookup_or_load(req.partition, &cache_key).await?;
+ let person = self.lookup_or_load(partition, &cache_key).await?;
Ok(Response::new(GetPersonResponse {
person: Some(cached_person_to_proto(&person)),
@@ -177,7 +230,9 @@ impl PersonHogLeader for PersonHogLeaderService {
&self,
request: Request<UpdatePersonPropertiesRequest>,
) -> Result<Response<UpdatePersonPropertiesResponse>, Status> {
+ let partition = partition_from_metadata(&request)?;
let req = request.into_inner();
+ self.validate_partition(partition, req.team_id, req.person_id)?;
// Track this write as inflight for its partition. The handoff protocol
// waits for the per-partition inflight count to drop to zero before
@@ -185,7 +240,7 @@ impl PersonHogLeader for PersonHogLeaderService {
// zero count implies every acked write is durable in Kafka. Using a
// non-`_` prefixed binding so the RAII guard is held for the full
// handler lifetime (see the `let_underscore_drop` lint).
- let _inflight_guard = self.inflight.begin(req.partition);
+ let _inflight_guard = self.inflight.begin(partition);
let cache_key = PersonCacheKey {
team_id: req.team_id,
@@ -218,9 +273,7 @@ impl PersonHogLeader for PersonHogLeaderService {
.clone();
let _guard = mutex.lock().await;
- let person = self
- .lookup_or_load_locked(req.partition, &cache_key)
- .await?;
+ let person = self.lookup_or_load_locked(partition, &cache_key).await?;
// Compute property updates
let updates = compute_event_property_updates(
@@ -267,7 +320,7 @@ impl PersonHogLeader for PersonHogLeaderService {
// Produce to Kafka first, then update the cache on success.
// Readers only ever see durably committed state.
if let Err(e) =
- produce_person_changelog(&self.producer, &self.changelog_topic, &proto).await
+ produce_person_changelog(&self.producer, &self.changelog_topic, partition, &proto).await
{
tracing::error!(
team_id = cache_key.team_id,
@@ -280,7 +333,7 @@ impl PersonHogLeader for PersonHogLeaderService {
)));
}
- self.cache.put(req.partition, cache_key, updated_person);
+ self.cache.put(partition, cache_key, updated_person);
counter!("personhog_leader_updates_total", "outcome" => "updated").increment(1);
Ok(Response::new(UpdatePersonPropertiesResponse {
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index eddb8536bbe0..33c7c0ad5d44 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -24,6 +24,7 @@ use rdkafka::mocking::MockCluster;
use rdkafka::producer::{DefaultProducerContext, FutureProducer};
use assignment_coordination::store::{EtcdStore, StoreConfig};
+use personhog_common::partitioning::partition_for_person;
use personhog_leader::cache::{CachedPerson, PartitionedCache, PersonCacheKey};
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::service::PersonHogLeaderService;
@@ -42,6 +43,15 @@ pub const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
pub const POLL_INTERVAL: Duration = Duration::from_millis(100);
pub const NUM_PARTITIONS: u32 = 4;
+/// Find a person_id whose key hashes to `partition`, so a test can aim a
+/// request at a specific partition while satisfying the leader's partition
+/// validation.
+pub fn person_id_for_partition(team_id: i64, partition: u32) -> i64 {
+ (1..)
+ .find(|pid| partition_for_person(team_id, *pid, NUM_PARTITIONS) == partition)
+ .expect("every partition is reachable from some person_id")
+}
+
pub async fn test_store(test_name: &str) -> Arc<PersonhogStore> {
let prefix = format!("/test-{}-{}/", test_name, uuid::Uuid::new_v4());
let config = StoreConfig {
@@ -315,6 +325,7 @@ pub async fn start_leader_pod(
None,
Arc::new(DashMap::new()),
Arc::clone(&inflight),
+ NUM_PARTITIONS,
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let leader_addr = listener.local_addr().unwrap();
@@ -378,6 +389,7 @@ pub async fn start_leader_pod_with_lease_ttl(
None,
Arc::new(DashMap::new()),
Arc::clone(&inflight),
+ NUM_PARTITIONS,
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let leader_addr = listener.local_addr().unwrap();
@@ -457,6 +469,7 @@ pub async fn start_leader_with_pg_fallback(
Some(pool),
Arc::new(DashMap::new()),
Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ NUM_PARTITIONS,
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 62dd4a07facc..140d6d749634 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -7,17 +7,19 @@ use dashmap::DashMap;
use common::{
create_leader_client, create_local_kafka_producer, create_test_kafka,
- create_test_kafka_with_partitions, seed_person, start_coordinator, start_leader_pod,
- start_leader_pod_with_lease_ttl, start_leader_with_pg_fallback, start_router,
+ create_test_kafka_with_partitions, person_id_for_partition, seed_person, start_coordinator,
+ start_leader_pod, start_leader_pod_with_lease_ttl, start_leader_with_pg_fallback, start_router,
test_cached_person, test_store, wait_for_condition, CHANGELOG_TOPIC, KAFKA_BOOTSTRAP,
NUM_PARTITIONS, POLL_INTERVAL, WAIT_TIMEOUT,
};
+use personhog_common::partitioning::partition_for_person;
use personhog_coordination::strategy::StickyBalancedStrategy;
use personhog_leader::cache::{CacheLookup, PartitionedCache};
use personhog_leader::service::PersonHogLeaderService;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
-use personhog_proto::personhog::leader::v1::LeaderGetPersonRequest;
-use personhog_proto::personhog::types::v1::{Person, UpdatePersonPropertiesRequest};
+use personhog_proto::personhog::types::v1::{
+ GetPersonRequest, Person, UpdatePersonPropertiesRequest,
+};
use prost::Message;
use rdkafka::consumer::{BaseConsumer, Consumer};
use rdkafka::types::{RDKafkaApiKey, RDKafkaRespErr};
@@ -25,6 +27,30 @@ use rdkafka::{ClientConfig, Message as KafkaMessage, TopicPartitionList};
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use tonic::transport::Server;
+use tonic::Request;
+
+/// Wrap a request with the `x-partition` metadata the leader reads in place
+/// of a body field, matching how the router forwards to the leader.
+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
+}
+
+/// Build a `GetPerson` request carrying the partition in `x-partition`
+/// metadata, matching how the router forwards strong reads to the leader.
+fn leader_get_request(team_id: i64, person_id: i64, partition: u32) -> Request<GetPersonRequest> {
+ with_partition(
+ GetPersonRequest {
+ team_id,
+ person_id,
+ read_options: None,
+ },
+ partition,
+ )
+}
// ============================================================
// Test 1: Full lifecycle via etcd coordination
@@ -82,11 +108,7 @@ async fn service_accepts_requests_after_coordination_warmup() {
// gRPC get_person should succeed
let mut client = create_leader_client(pod.leader_addr).await;
let response = client
- .get_person(LeaderGetPersonRequest {
- team_id: 1,
- person_id: 42,
- partition: 0,
- })
+ .get_person(leader_get_request(1, 42, 0))
.await
.unwrap();
@@ -96,15 +118,18 @@ async fn service_accepts_requests_after_coordination_warmup() {
// Update should succeed
let response = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "Updated"})).unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Updated"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ 0,
+ ))
.await
.unwrap();
@@ -114,11 +139,7 @@ async fn service_accepts_requests_after_coordination_warmup() {
// Read back should reflect the update
let response = client
- .get_person(LeaderGetPersonRequest {
- team_id: 1,
- person_id: 42,
- partition: 0,
- })
+ .get_person(leader_get_request(1, 42, 0))
.await
.unwrap();
@@ -149,6 +170,7 @@ async fn unowned_partition_returns_failed_precondition() {
None,
Arc::new(DashMap::new()),
Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ NUM_PARTITIONS,
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -171,17 +193,95 @@ async fn unowned_partition_returns_failed_precondition() {
let mut client = create_leader_client(addr).await;
// Request for unowned partition → FailedPrecondition
+ let result = client.get_person(leader_get_request(1, 42, 0)).await;
+ assert!(result.is_err());
+ assert_eq!(result.unwrap_err().code(), tonic::Code::FailedPrecondition);
+
+ // Write to unowned partition → FailedPrecondition
let result = client
- .get_person(LeaderGetPersonRequest {
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: vec![],
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ 0,
+ ))
+ .await;
+ assert!(result.is_err());
+ assert_eq!(result.unwrap_err().code(), tonic::Code::FailedPrecondition);
+
+ // Manually warm partition → now NotFound (partition exists, no data)
+ cache.create_partition(0);
+
+ let result = client.get_person(leader_get_request(1, 42, 0)).await;
+ assert!(result.is_err());
+ assert_eq!(result.unwrap_err().code(), tonic::Code::NotFound);
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Test 2b: Requests without x-partition metadata fail closed
+// (no etcd needed)
+// ============================================================
+
+/// The partition arrives only via `x-partition` metadata, stamped by the
+/// router. A request without it is misrouted or malformed and must be
+/// rejected with INVALID_ARGUMENT rather than served against a guessed
+/// partition — even when the person exists and its partition is warm.
+#[tokio::test]
+async fn missing_partition_metadata_returns_invalid_argument() {
+ let cache = Arc::new(PartitionedCache::new(100));
+ let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ NUM_PARTITIONS,
+ );
+
+ // Warm the partition and seed the person so the only failure mode
+ // left is the missing metadata itself.
+ cache.create_partition(0);
+ seed_person(&cache, 0, test_cached_person());
+
+ 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;
+
+ let mut client = create_leader_client(addr).await;
+
+ let result = client
+ .get_person(GetPersonRequest {
team_id: 1,
person_id: 42,
- partition: 0,
+ read_options: None,
})
.await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::FailedPrecondition);
+ let status = result.expect_err("read without x-partition must fail closed");
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ assert!(status.message().contains("x-partition"));
- // Write to unowned partition → FailedPrecondition
let result = client
.update_person_properties(UpdatePersonPropertiesRequest {
team_id: 1,
@@ -190,24 +290,89 @@ async fn unowned_partition_returns_failed_precondition() {
set_properties: vec![],
set_once_properties: vec![],
unset_properties: vec![],
- partition: 0,
})
.await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::FailedPrecondition);
+ let status = result.expect_err("write without x-partition must fail closed");
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ assert!(status.message().contains("x-partition"));
- // Manually warm partition → now NotFound (partition exists, no data)
- cache.create_partition(0);
+ cancel.cancel();
+}
+
+// ============================================================
+// Test 2c: x-partition must match the partition derived from the
+// request's own key (no etcd needed)
+// ============================================================
+
+/// The leader validates the router's routing decision against the decoded
+/// body: `x-partition` must equal `partition_for_person(team_id,
+/// person_id)`. A mismatch means a client stamped wrong routing-key
+/// headers or the hash implementations diverged — serving it would read or
+/// write through the wrong partition's cache, so it must be rejected even
+/// when the named partition is warm and the person exists there.
+#[tokio::test]
+async fn mismatched_partition_metadata_returns_invalid_argument() {
+ let cache = Arc::new(PartitionedCache::new(100));
+ let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ NUM_PARTITIONS,
+ );
+
+ // Key (1, 42) hashes to some true partition; pick a different one and
+ // warm + seed it so the only failure mode left is the mismatch itself.
+ let true_partition = partition_for_person(1, 42, NUM_PARTITIONS);
+ let wrong_partition = (true_partition + 1) % NUM_PARTITIONS;
+ cache.create_partition(wrong_partition);
+ seed_person(&cache, wrong_partition, test_cached_person());
+
+ 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;
+
+ let mut client = create_leader_client(addr).await;
let result = client
- .get_person(LeaderGetPersonRequest {
- team_id: 1,
- person_id: 42,
- partition: 0,
- })
+ .get_person(leader_get_request(1, 42, wrong_partition))
.await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::NotFound);
+ let status = result.expect_err("read with mismatched x-partition must fail closed");
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ assert!(status.message().contains("does not match"));
+
+ let result = client
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: vec![],
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ wrong_partition,
+ ))
+ .await;
+ let status = result.expect_err("write with mismatched x-partition must fail closed");
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ assert!(status.message().contains("does not match"));
cancel.cancel();
}
@@ -260,11 +425,7 @@ async fn release_partition_stops_serving() {
// Verify get_person works on pod 1
let mut client1 = create_leader_client(pod1.leader_addr).await;
let response = client1
- .get_person(LeaderGetPersonRequest {
- team_id: 1,
- person_id: 42,
- partition: 0,
- })
+ .get_person(leader_get_request(1, 42, 0))
.await
.unwrap();
assert_eq!(response.into_inner().person.unwrap().id, 42);
@@ -304,13 +465,13 @@ async fn release_partition_stops_serving() {
})
.await;
+ // A key that actually hashes to the moved partition, so the request
+ // passes the leader's partition validation.
+ let moved_person_id = person_id_for_partition(1, moved_partition);
+
// Pod 1: released partition → FailedPrecondition
let result = client1
- .get_person(LeaderGetPersonRequest {
- team_id: 1,
- person_id: 42,
- partition: moved_partition,
- })
+ .get_person(leader_get_request(1, moved_person_id, moved_partition))
.await;
assert!(result.is_err());
assert_eq!(
@@ -322,11 +483,7 @@ async fn release_partition_stops_serving() {
// Pod 2: warmed partition but empty cache → NotFound
let mut client2 = create_leader_client(pod2.leader_addr).await;
let result = client2
- .get_person(LeaderGetPersonRequest {
- team_id: 1,
- person_id: 42,
- partition: moved_partition,
- })
+ .get_person(leader_get_request(1, moved_person_id, moved_partition))
.await;
assert!(result.is_err());
assert_eq!(
@@ -413,13 +570,7 @@ async fn rewarm_after_pod_crash() {
// Partitions are warm but empty → NotFound
let mut client2 = create_leader_client(pod2.leader_addr).await;
- let result = client2
- .get_person(LeaderGetPersonRequest {
- team_id: 1,
- person_id: 42,
- partition: 0,
- })
- .await;
+ let result = client2.get_person(leader_get_request(1, 42, 0)).await;
assert!(result.is_err());
assert_eq!(result.unwrap_err().code(), tonic::Code::NotFound);
@@ -433,13 +584,21 @@ async fn rewarm_after_pod_crash() {
#[tokio::test]
async fn update_produces_person_state_to_kafka() {
- let cache = Arc::new(PartitionedCache::new(100));
- // Single-partition topic: this test verifies the producer's delivery
- // path, not partition routing. Using a single partition makes the
- // assertion (consume from partition 0) deterministic regardless of
- // rdkafka's default key-hash partitioner.
- let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(1).await;
+ // The changelog must land on the exact Kafka partition the request's
+ // `x-partition` named — warming rebuilds a routing partition's cache by
+ // consuming the same-numbered Kafka partition, so key-hash placement
+ // (whose partitioner config could diverge from the router's murmur2)
+ // is not acceptable. The key (team 1, person 2) murmur2-hashes to
+ // partition 2 (so it passes the leader's partition validation) but
+ // librdkafka's default crc32 partitioner would place it on partition 0,
+ // keeping misplacement observable: the consumer below reads only
+ // partition 2 and must find the message there.
+ const PERSON_ID: i64 = 2;
+ let routing_partition: u32 = partition_for_person(1, PERSON_ID, NUM_PARTITIONS);
+ assert_eq!(routing_partition, 2, "test key must map to partition 2");
+ let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
+ let cache = Arc::new(PartitionedCache::new(100));
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
kafka_producer,
@@ -447,11 +606,15 @@ async fn update_produces_person_state_to_kafka() {
None,
Arc::new(DashMap::new()),
Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ NUM_PARTITIONS,
);
- cache.create_partition(0);
- let person = test_cached_person();
- seed_person(&cache, 0, person);
+ cache.create_partition(routing_partition);
+ let person = personhog_leader::cache::CachedPerson {
+ id: PERSON_ID,
+ ..test_cached_person()
+ };
+ seed_person(&cache, routing_partition, person);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
@@ -474,15 +637,18 @@ async fn update_produces_person_state_to_kafka() {
// Perform an update
let response = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "Kafka Test"})).unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: PERSON_ID,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Kafka Test"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ routing_partition,
+ ))
.await
.unwrap();
@@ -490,7 +656,8 @@ async fn update_produces_person_state_to_kafka() {
assert!(result.updated);
assert_eq!(result.person.unwrap().version, 2);
- // Consume the message from the mock Kafka cluster
+ // Consume only the routing partition — finding the message here proves
+ // the explicit-partition produce, not just delivery.
let consumer: BaseConsumer = ClientConfig::new()
.set("bootstrap.servers", mock_cluster.bootstrap_servers())
.set("group.id", "test-consumer")
@@ -498,22 +665,26 @@ async fn update_produces_person_state_to_kafka() {
.expect("failed to create consumer");
let mut tpl = TopicPartitionList::new();
- tpl.add_partition_offset(CHANGELOG_TOPIC, 0, rdkafka::Offset::Beginning)
- .unwrap();
+ tpl.add_partition_offset(
+ CHANGELOG_TOPIC,
+ routing_partition as i32,
+ rdkafka::Offset::Beginning,
+ )
+ .unwrap();
consumer.assign(&tpl).unwrap();
let msg = consumer
.poll(Duration::from_secs(5))
- .expect("no message received")
+ .expect("no message received on the routing partition")
.expect("kafka error");
// Verify message key
let key = std::str::from_utf8(msg.key().unwrap()).unwrap();
- assert_eq!(key, "1:42");
+ assert_eq!(key, "1:2");
// Verify payload is a valid Person proto with updated state
let person = Person::decode(msg.payload().unwrap()).unwrap();
- assert_eq!(person.id, 42);
+ assert_eq!(person.id, PERSON_ID);
assert_eq!(person.team_id, 1);
assert_eq!(person.version, 2);
@@ -541,6 +712,7 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
None,
Arc::new(DashMap::new()),
Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ NUM_PARTITIONS,
);
cache.create_partition(0);
@@ -572,16 +744,18 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
// Update should fail because Kafka produce fails
let result = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "Should Rollback"}))
- .unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Should Rollback"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ 0,
+ ))
.await;
assert!(result.is_err());
@@ -603,16 +777,18 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
mock_cluster.clear_request_errors(RDKafkaApiKey::Produce);
let response = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "After Recovery"}))
- .unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "After Recovery"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ 0,
+ ))
.await
.unwrap();
@@ -640,6 +816,7 @@ async fn e2e_update_produces_to_local_kafka() {
None,
Arc::new(DashMap::new()),
Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ NUM_PARTITIONS,
);
cache.create_partition(0);
@@ -667,15 +844,18 @@ async fn e2e_update_produces_to_local_kafka() {
// Perform an update via gRPC
let response = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "E2E Test"})).unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "E2E Test"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ 0,
+ ))
.await
.unwrap();
@@ -738,9 +918,6 @@ async fn pg_fallback_loads_person_on_cache_miss() {
let cancel = CancellationToken::new();
let (addr, cache, _mock_cluster) = start_leader_with_pg_fallback(cancel.clone()).await;
- // Warm partition 0 (the cache is empty — no persons seeded)
- cache.create_partition(0);
-
// Find a real person in the local DB to query
let pool = common::create_persons_pool().await;
let row: Option<(i64, i32)> = sqlx::query_as("SELECT id, team_id FROM posthog_person LIMIT 1")
@@ -754,15 +931,15 @@ async fn pg_fallback_loads_person_on_cache_miss() {
return;
};
+ // Warm the key's own partition (the cache is empty — no persons seeded)
+ let partition = partition_for_person(team_id as i64, person_id, NUM_PARTITIONS);
+ cache.create_partition(partition);
+
let mut client = create_leader_client(addr).await;
// First call: cache miss → PG fallback → loads and caches the person
let response = client
- .get_person(LeaderGetPersonRequest {
- team_id: team_id as i64,
- person_id,
- partition: 0,
- })
+ .get_person(leader_get_request(team_id as i64, person_id, partition))
.await
.unwrap();
@@ -777,7 +954,7 @@ async fn pg_fallback_loads_person_on_cache_miss() {
};
assert!(
matches!(
- cache.get(0, &key),
+ cache.get(partition, &key),
personhog_leader::cache::CacheLookup::Found(_)
),
"person should be cached after PG fallback"
@@ -795,17 +972,14 @@ async fn pg_fallback_returns_not_found_for_missing_person() {
let cancel = CancellationToken::new();
let (addr, cache, _mock_cluster) = start_leader_with_pg_fallback(cancel.clone()).await;
- cache.create_partition(0);
+ let partition = partition_for_person(99999, 99999999, NUM_PARTITIONS);
+ cache.create_partition(partition);
let mut client = create_leader_client(addr).await;
// Query a person that doesn't exist in PG
let result = client
- .get_person(LeaderGetPersonRequest {
- team_id: 99999,
- person_id: 99999999,
- partition: 0,
- })
+ .get_person(leader_get_request(99999, 99999999, partition))
.await;
assert!(result.is_err());
@@ -823,8 +997,6 @@ async fn update_triggers_pg_fallback_then_applies_changes() {
let cancel = CancellationToken::new();
let (addr, cache, _mock_cluster) = start_leader_with_pg_fallback(cancel.clone()).await;
- cache.create_partition(0);
-
// Find a real person to update
let pool = common::create_persons_pool().await;
let row: Option<(i64, i32)> = sqlx::query_as("SELECT id, team_id FROM posthog_person LIMIT 1")
@@ -838,22 +1010,27 @@ async fn update_triggers_pg_fallback_then_applies_changes() {
return;
};
+ let partition = partition_for_person(team_id as i64, person_id, NUM_PARTITIONS);
+ cache.create_partition(partition);
+
let mut client = create_leader_client(addr).await;
// Update a person not in cache — should load from PG then apply
let response = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: team_id as i64,
- person_id,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({
- "pg_fallback_test": "it_works"
- }))
- .unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: team_id as i64,
+ person_id,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({
+ "pg_fallback_test": "it_works"
+ }))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ partition,
+ ))
.await
.unwrap();
diff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rs
index f7ef499018b2..ee9682d1e143 100644
--- a/rust/personhog-replica/src/main.rs
+++ b/rust/personhog-replica/src/main.rs
@@ -358,16 +358,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Some(age) = max_connection_age {
server = server.max_connection_age(age);
}
+ // accept_compressed only decodes gzip request frames from opted-in
+ // clients; response compression is exclusively the gzip layer above
+ // (never send_compressed — see the tonic entry in Cargo.toml). Note
+ // max_decoding_message_size bounds the wire (compressed) size, so a
+ // compressed request can decode larger than the limit.
if let Err(e) = server
.layer(AsyncGzipLayer::new(gzip_config))
.layer(GrpcMetricsLayer::default().with_processing_time_header())
.layer(GrpcLoadShedLayer::new(max_concurrent_requests))
.add_service(
PersonHogReplicaServer::new(service)
+ .accept_compressed(CompressionEncoding::Gzip)
.max_encoding_message_size(max_send)
- .max_decoding_message_size(max_recv)
- .accept_compressed(CompressionEncoding::Zstd)
- .send_compressed(CompressionEncoding::Zstd),
+ .max_decoding_message_size(max_recv),
)
.serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
.await
diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rs
index 131cde02556d..d977dd1886e0 100644
--- a/rust/personhog-router/src/backend/leader.rs
+++ b/rust/personhog-router/src/backend/leader.rs
@@ -1,37 +1,38 @@
use std::collections::HashMap;
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
-use async_trait::async_trait;
+use bytes::Bytes;
use dashmap::DashMap;
-use personhog_proto::personhog::leader::v1::person_hog_leader_client::PersonHogLeaderClient;
-use personhog_proto::personhog::leader::v1::LeaderGetPersonRequest;
-use personhog_proto::personhog::types::v1::{
- GetPersonRequest, GetPersonResponse, UpdatePersonPropertiesRequest,
- UpdatePersonPropertiesResponse,
-};
+use http::{HeaderMap, HeaderValue, Method, Uri, Version};
+use http_body_util::{BodyExt, Full};
+use metrics::histogram;
use tokio::sync::RwLock;
-use tonic::codec::CompressionEncoding;
+use tonic::body::BoxBody;
use tonic::transport::Channel;
-use tonic::{Request, Status};
+use tonic::{Code, Status};
+use tower::{Service, ServiceExt};
-use personhog_common::grpc::{current_caller_tag, current_client_name};
+use personhog_common::grpc::current_client_name;
+use personhog_common::partitioning::partition_for_person;
use super::retry::with_retry;
use super::stash::{StashDecision, StashTable};
-use super::LeaderOps;
use crate::config::RetryConfig;
+use crate::grpc_http::grpc_error_response;
pub type AddressResolver = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
+/// gRPC path prefix for the leader service; raw forwards target
+/// `{LEADER_PREFIX}{method}`.
+const LEADER_PREFIX: &str = "/personhog.leader.v1.PersonHogLeader/";
+
/// Static configuration for `LeaderBackend`. Bundles the knobs that come
/// from `Config` so the constructor stays narrow as we add fields.
pub struct LeaderBackendConfig {
pub num_partitions: u32,
pub timeout: Duration,
pub retry_config: RetryConfig,
- pub max_send_message_size: usize,
- pub max_recv_message_size: usize,
}
/// Backend that routes person writes and strong reads to leader pods
@@ -39,8 +40,10 @@ pub struct LeaderBackendConfig {
pub struct LeaderBackend {
/// Read-only handle to the routing table (partition → pod_name).
routing_table: Arc<RwLock<HashMap<u32, String>>>,
- /// Cached gRPC clients keyed by pod gRPC address.
- clients: DashMap<String, PersonHogLeaderClient<Channel>>,
+ /// Cached gRPC channels keyed by pod gRPC address. All leader traffic —
+ /// strong reads and writes — forwards raw request frames over these
+ /// channels.
+ channels: DashMap<String, Channel>,
/// Resolves pod_name → gRPC address.
address_resolver: AddressResolver,
config: LeaderBackendConfig,
@@ -63,7 +66,7 @@ impl LeaderBackend {
);
Self {
routing_table,
- clients: DashMap::new(),
+ channels: DashMap::new(),
address_resolver,
config,
stash,
@@ -76,36 +79,25 @@ impl LeaderBackend {
self.stash.clone()
}
- /// Remove cached gRPC client for a pod so the next request reconnects.
- /// Called during partition handoff cutover to drop the connection to the
- /// old leader pod.
+ /// Remove the cached gRPC channel for a pod so the next request
+ /// reconnects. Called during partition handoff cutover to drop the
+ /// connection to the old leader pod.
pub fn clear_client_cache(&self, pod_name: &str) {
if let Some(address) = (self.address_resolver)(pod_name) {
- self.clients.remove(&address);
+ self.channels.remove(&address);
}
}
/// Compute the Kafka partition for a person using murmur2.
/// The key is `team_id:person_id`, matching the Kafka topic key.
pub fn partition_for_person(&self, team_id: i64, person_id: i64) -> u32 {
- // i64 max string length is 20 chars. Two i64s + ':' = 41 bytes max.
- let mut buf = [0u8; 41];
- let len = {
- use std::io::Write;
- let mut cursor = std::io::Cursor::new(&mut buf[..]);
- write!(cursor, "{team_id}:{person_id}").unwrap();
- cursor.position() as usize
- };
- let hash = kafka_murmur2(&buf[..len]);
- let positive = (hash & 0x7fffffff) as u32;
- positive % self.config.num_partitions
+ partition_for_person(team_id, person_id, self.config.num_partitions)
}
- /// Resolve the leader gRPC client for a given partition.
- async fn resolve_leader(
- &self,
- partition: u32,
- ) -> Result<PersonHogLeaderClient<Channel>, Status> {
+ /// Resolve the leader gRPC channel for a given partition, building and
+ /// caching a lazy channel on first use. All leader traffic — strong
+ /// reads and writes — forwards raw requests over this channel.
+ pub async fn resolve_leader_channel(&self, partition: u32) -> Result<Channel, Status> {
let pod_name = self
.routing_table
.read()
@@ -120,8 +112,8 @@ impl LeaderBackend {
Status::unavailable(format!("cannot resolve address for pod {pod_name}"))
})?;
- if let Some(client) = self.clients.get(&address) {
- return Ok(client.clone());
+ if let Some(channel) = self.channels.get(&address) {
+ return Ok(channel.clone());
}
let channel = Channel::from_shared(address.clone())
@@ -129,199 +121,131 @@ impl LeaderBackend {
.timeout(self.config.timeout)
.tcp_nodelay(true)
.connect_lazy();
- let client = PersonHogLeaderClient::new(channel)
- .max_encoding_message_size(self.config.max_send_message_size)
- .max_decoding_message_size(self.config.max_recv_message_size)
- .send_compressed(CompressionEncoding::Zstd)
- .accept_compressed(CompressionEncoding::Zstd);
- self.clients.insert(address, client.clone());
- Ok(client)
- }
-}
-
-/// Kafka-compatible murmur2 hash.
-///
-/// This matches the Java Kafka client's `Utils.murmur2()` implementation
-/// so that partition assignment is consistent with Kafka's default partitioner.
-fn kafka_murmur2(data: &[u8]) -> i32 {
- let length = data.len();
- let seed: i32 = 0x9747b28cu32 as i32;
- let m: i32 = 0x5bd1e995u32 as i32;
- let r: u32 = 24;
-
- let mut h: i32 = seed ^ (length as i32);
-
- let length4 = length / 4;
- for i in 0..length4 {
- let i4 = i * 4;
- let mut k: i32 = (data[i4] as i32 & 0xff)
- | ((data[i4 + 1] as i32 & 0xff) << 8)
- | ((data[i4 + 2] as i32 & 0xff) << 16)
- | ((data[i4 + 3] as i32 & 0xff) << 24);
-
- k = k.wrapping_mul(m);
- k ^= (k as u32 >> r) as i32;
- k = k.wrapping_mul(m);
- h = h.wrapping_mul(m);
- h ^= k;
- }
-
- let tail = length & !3;
- match length % 4 {
- 3 => {
- h ^= (data[tail + 2] as i32 & 0xff) << 16;
- h ^= (data[tail + 1] as i32 & 0xff) << 8;
- h ^= data[tail] as i32 & 0xff;
- h = h.wrapping_mul(m);
- }
- 2 => {
- h ^= (data[tail + 1] as i32 & 0xff) << 8;
- h ^= data[tail] as i32 & 0xff;
- h = h.wrapping_mul(m);
- }
- 1 => {
- h ^= data[tail] as i32 & 0xff;
- h = h.wrapping_mul(m);
- }
- _ => {}
+ self.channels.insert(address, channel.clone());
+ Ok(channel)
}
- h ^= (h as u32 >> 13) as i32;
- h = h.wrapping_mul(m);
- h ^= (h as u32 >> 15) as i32;
-
- h
-}
-
-#[async_trait]
-impl LeaderOps for LeaderBackend {
- async fn get_person(&self, request: GetPersonRequest) -> Result<GetPersonResponse, Status> {
- let partition = self.partition_for_person(request.team_id, request.person_id);
- let leader_req = LeaderGetPersonRequest {
- team_id: request.team_id,
- person_id: request.person_id,
- partition,
- };
- with_retry(&self.config.retry_config, "get_person", || {
- let client_fut = self.resolve_leader(partition);
- let req = leader_req;
- let client_name = current_client_name();
- let caller_tag = current_caller_tag();
+ /// Forward a raw gRPC request frame to the leader pod owning
+ /// `partition`, retrying transient channel failures. The partition
+ /// travels in the `x-partition` header the leader reads in place of a
+ /// body field; the client's own headers (`x-client-name`,
+ /// `x-caller-tag`, etc.) are forwarded verbatim. A leader response that
+ /// carries a gRPC error is returned as `Ok` — only transport failures
+ /// retry and surface as `Err`. On success also returns the channel
+ /// round-trip time, used by the read path's network-overhead metric.
+ pub async fn forward_raw(
+ &self,
+ method: &'static str,
+ partition: u32,
+ headers: &HeaderMap,
+ frame: &Bytes,
+ ) -> Result<(http::Response<BoxBody>, f64), Status> {
+ let path = format!("{LEADER_PREFIX}{method}");
+ let partition_header = HeaderValue::from(partition);
+ let client = current_client_name();
+
+ with_retry(&self.config.retry_config, method, || {
+ let channel_fut = self.resolve_leader_channel(partition);
+ let headers = headers.clone();
+ let frame = frame.clone();
+ let path = path.clone();
+ let partition_header = partition_header.clone();
+ let client = client.clone();
async move {
- let mut client = client_fut.await?;
- let mut request = Request::new(req);
- if let Ok(val) = client_name.parse() {
- request.metadata_mut().insert("x-client-name", val);
- }
- if let Ok(val) = caller_tag.parse() {
- request.metadata_mut().insert("x-caller-tag", val);
- }
- client.get_person(request).await.map(|r| r.into_inner())
+ let mut channel = channel_fut.await?;
+
+ let ready_start = Instant::now();
+ let ready_result = channel.ready().await;
+ let ready_outcome = if ready_result.is_ok() { "ok" } else { "error" };
+ histogram!(
+ "personhog_router_channel_ready_wait_ms",
+ "method" => method,
+ "client" => client.clone(),
+ "outcome" => ready_outcome,
+ )
+ .record(ready_start.elapsed().as_secs_f64() * 1000.0);
+ let ready = ready_result
+ .map_err(|e| Status::unavailable(format!("leader channel not ready: {e}")))?;
+
+ let body = BoxBody::new(Full::new(frame).map_err(|never| match never {}));
+ let mut req = http::Request::new(body);
+ *req.method_mut() = Method::POST;
+ *req.uri_mut() = Uri::builder()
+ .path_and_query(path)
+ .build()
+ .expect("leader path is a valid URI");
+ *req.version_mut() = Version::HTTP_2;
+ *req.headers_mut() = headers;
+ req.headers_mut().insert("x-partition", partition_header);
+
+ let call_start = Instant::now();
+ let call_result = ready.call(req).await;
+ let call_ms = call_start.elapsed().as_secs_f64() * 1000.0;
+ let call_outcome = if call_result.is_ok() { "ok" } else { "error" };
+ histogram!(
+ "personhog_router_channel_call_ms",
+ "method" => method,
+ "client" => client,
+ "outcome" => call_outcome,
+ )
+ .record(call_ms);
+ let response = call_result
+ .map_err(|e| Status::unavailable(format!("leader backend error: {e}")))?;
+ Ok((response, call_ms))
}
})
.await
}
- async fn update_person_properties(
+ /// Forward a write to the leader, honoring the per-partition stash.
+ /// While a handoff for this partition is in a non-terminal phase the
+ /// stash is open and the request parks until drain replays it to the
+ /// new owner (or its deadline expires); otherwise it forwards
+ /// immediately. Returns the final gRPC response — the leader's, or a
+ /// router-generated error when the stash is full or dropped — plus the
+ /// channel round-trip time when the request forwarded directly
+ /// (`None` for stashed requests, whose latency is dominated by the
+ /// handoff wait and tracked by the stash-wait histogram instead).
+ pub async fn forward_or_stash(
&self,
- request: UpdatePersonPropertiesRequest,
- ) -> Result<UpdatePersonPropertiesResponse, Status> {
- let partition = self.partition_for_person(request.team_id, request.person_id);
- let mut req_with_partition = request;
- req_with_partition.partition = partition;
-
- // Stash fast path. While a handoff for this partition is in any
- // non-terminal phase (`Freezing`, `Draining`, or `Warming`), the
- // partition is registered in the stash table and writes are
- // queued instead of forwarded. The coordinator atomically writes
- // `Complete` together with the new `PartitionAssignment`; at
- // that point `drain_stash` flushes the queue to the new owner
- // via `update_person_properties_no_stash` (bypassing this hook
- // to avoid re-enqueueing during drain), and subsequent requests
- // fall through to the normal forward path below.
- // The stash module emits its own enqueued/rejected counters with
- // appropriate labels at the source; we don't double-count here.
+ method: &'static str,
+ partition: u32,
+ key: (i64, i64),
+ headers: HeaderMap,
+ frame: Bytes,
+ ) -> (http::Response<BoxBody>, Option<f64>) {
+ // The stash module emits its own enqueued/rejected counters at the
+ // source; we don't double-count here. It borrows the frame and
+ // headers, cloning only when the request actually parks, so the
+ // steady-state forward path copies nothing.
match self
.stash
- .enqueue_or_forward(
- partition,
- req_with_partition.clone(),
- Some(current_client_name().to_string()),
- )
+ .enqueue_or_forward(partition, &frame, &headers, key)
.await
{
StashDecision::Stashed(rx) => {
- return rx.await.unwrap_or_else(|_| {
- Err(Status::unavailable(
+ let response = rx.await.unwrap_or_else(|_| {
+ grpc_error_response(
+ Code::Unavailable,
"router stash dropped before handoff completed",
- ))
+ )
});
+ (response, None)
}
- StashDecision::Rejected => {
- return Err(Status::unavailable(format!(
- "router stash full for partition {partition}"
- )));
+ StashDecision::Rejected => (
+ grpc_error_response(
+ Code::Unavailable,
+ &format!("router stash full for partition {partition}"),
+ ),
+ None,
+ ),
+ StashDecision::Forward => {
+ match self.forward_raw(method, partition, &headers, &frame).await {
+ Ok((response, call_ms)) => (response, Some(call_ms)),
+ Err(status) => (grpc_error_response(status.code(), status.message()), None),
+ }
}
- StashDecision::Forward => {}
}
-
- self.forward_to_leader(req_with_partition, partition).await
- }
-}
-
-impl LeaderBackend {
- /// Forward an update directly to the leader, bypassing the stash
- /// hook. Used by the drain handler so each replayed request goes to
- /// the leader instead of re-entering the stash queue (which would
- /// deadlock the drain — the dashmap entry is still present until
- /// the drain loop observes the queue empty under the lock).
- ///
- /// Callers that want the normal stash-aware path should call
- /// `update_person_properties` instead. This method assumes its
- /// caller has already computed the correct partition and stamped
- /// it onto the request.
- pub async fn update_person_properties_no_stash(
- &self,
- request: UpdatePersonPropertiesRequest,
- ) -> Result<UpdatePersonPropertiesResponse, Status> {
- let partition = request.partition;
- self.forward_to_leader(request, partition).await
- }
-
- /// Internal: do the actual gRPC forward to the leader for a given
- /// partition, with retry on transient errors. Shared between the
- /// normal `update_person_properties` (post-stash) and the drain's
- /// `update_person_properties_no_stash` path.
- async fn forward_to_leader(
- &self,
- request: UpdatePersonPropertiesRequest,
- partition: u32,
- ) -> Result<UpdatePersonPropertiesResponse, Status> {
- with_retry(
- &self.config.retry_config,
- "update_person_properties",
- || {
- let client_fut = self.resolve_leader(partition);
- let req = request.clone();
- let client_name = current_client_name();
- let caller_tag = current_caller_tag();
- async move {
- let mut client = client_fut.await?;
- let mut request = Request::new(req);
- if let Ok(val) = client_name.parse() {
- request.metadata_mut().insert("x-client-name", val);
- }
- if let Ok(val) = caller_tag.parse() {
- request.metadata_mut().insert("x-caller-tag", val);
- }
- client
- .update_person_properties(request)
- .await
- .map(|r| r.into_inner())
- }
- },
- )
- .await
}
}
@@ -338,93 +262,6 @@ mod tests {
initial_backoff_ms: 1,
max_backoff_ms: 1,
},
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
- }
- }
-
- #[test]
- fn murmur2_deterministic_and_consistent() {
- // Same input always produces same hash
- let h1 = kafka_murmur2(b"42");
- let h2 = kafka_murmur2(b"42");
- assert_eq!(h1, h2);
-
- // Different inputs produce different hashes
- let h3 = kafka_murmur2(b"43");
- assert_ne!(h1, h3);
- }
-
- /// Pin murmur2 output so accidental algorithm changes are caught.
- /// These values must match `org.apache.kafka.common.utils.Utils.murmur2()`
- /// to ensure partition assignment is consistent with Kafka's default partitioner.
- #[test]
- fn murmur2_pinned_values() {
- assert_eq!(kafka_murmur2(b""), 275646681);
- assert_eq!(kafka_murmur2(b"21"), -973932308);
- assert_eq!(kafka_murmur2(b"42"), 417700972);
- assert_eq!(kafka_murmur2(b"1:42"), -1141388408);
- assert_eq!(kafka_murmur2(b"hello"), 2132663229);
- assert_eq!(kafka_murmur2(b"test-key"), -1341026247);
- }
-
- #[test]
- fn murmur2_kafka_partition_assignment() {
- // Kafka's toPositive: hash & 0x7fffffff
- let hash = kafka_murmur2(b"21");
- let positive = (hash & 0x7fffffff) as u32;
- let partition = positive % 16;
- assert!(partition < 16);
-
- // Same input always produces same partition
- let hash2 = kafka_murmur2(b"21");
- assert_eq!(hash, hash2);
- }
-
- #[test]
- fn partition_for_person_deterministic() {
- let routing_table = Arc::new(RwLock::new(HashMap::new()));
- let resolver: AddressResolver = Arc::new(|_| Some("http://localhost:50053".to_string()));
- let backend = LeaderBackend::new(
- routing_table,
- resolver,
- test_config(16),
- StashTable::with_bounds(usize::MAX, usize::MAX),
- );
-
- let p1 = backend.partition_for_person(1, 42);
- let p2 = backend.partition_for_person(1, 42);
- assert_eq!(p1, p2);
- assert!(p1 < 16);
-
- // Different person_ids should (likely) produce different partitions
- let p3 = backend.partition_for_person(1, 43);
- assert!(p3 < 16);
- }
-
- #[test]
- fn partition_distribution_is_reasonable() {
- let routing_table = Arc::new(RwLock::new(HashMap::new()));
- let resolver: AddressResolver = Arc::new(|_| Some("http://localhost:50053".to_string()));
- let backend = LeaderBackend::new(
- routing_table,
- resolver,
- test_config(8),
- StashTable::with_bounds(usize::MAX, usize::MAX),
- );
-
- let mut counts = [0u32; 8];
- for person_id in 1..=1000 {
- let partition = backend.partition_for_person(1, person_id);
- counts[partition as usize] += 1;
- }
-
- // Each partition should get at least some keys (rough check)
- for (i, count) in counts.iter().enumerate() {
- assert!(
- *count > 50,
- "partition {i} only got {count} keys out of 1000"
- );
}
}
@@ -440,7 +277,7 @@ mod tests {
);
let partition = backend.partition_for_person(1, 42);
- let result = backend.resolve_leader(partition).await;
+ let result = backend.resolve_leader_channel(partition).await;
assert!(result.is_err());
assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
}
@@ -462,7 +299,7 @@ mod tests {
.insert(partition, "leader-0".to_string());
let partition = backend.partition_for_person(1, 42);
- let result = backend.resolve_leader(partition).await;
+ let result = backend.resolve_leader_channel(partition).await;
assert!(result.is_err());
assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
}
@@ -485,12 +322,12 @@ mod tests {
.insert(partition, "leader-0".to_string());
let partition = backend.partition_for_person(1, 42);
- let result = backend.resolve_leader(partition).await;
+ let result = backend.resolve_leader_channel(partition).await;
assert!(result.is_ok());
}
#[tokio::test]
- async fn resolve_leader_caches_client() {
+ async fn resolve_leader_caches_channel() {
let routing_table = Arc::new(RwLock::new(HashMap::new()));
let resolver: AddressResolver = Arc::new(|_| Some("http://localhost:50053".to_string()));
let backend = LeaderBackend::new(
@@ -507,23 +344,19 @@ mod tests {
.insert(partition, "leader-0".to_string());
let partition = backend.partition_for_person(1, 42);
- let _client1 = backend.resolve_leader(partition).await.unwrap();
- assert_eq!(backend.clients.len(), 1);
+ let _channel1 = backend.resolve_leader_channel(partition).await.unwrap();
+ assert_eq!(backend.channels.len(), 1);
- let _client2 = backend.resolve_leader(partition).await.unwrap();
- assert_eq!(backend.clients.len(), 1); // still 1, cached
+ let _channel2 = backend.resolve_leader_channel(partition).await.unwrap();
+ assert_eq!(backend.channels.len(), 1); // still 1, cached
}
- /// When the partition's stash is open and full, `update_person_properties`
- /// must short-circuit with `Status::unavailable` instead of falling
- /// through to the forward path. This proves the stash-rejection branch
- /// in `update_person_properties` and that callers see a retryable
- /// error code rather than getting their request silently dropped.
+ /// When the partition's stash is open and full, `forward_or_stash`
+ /// must short-circuit with an UNAVAILABLE gRPC response instead of
+ /// forwarding, so callers see a retryable status rather than getting
+ /// their write silently dropped.
#[tokio::test]
- async fn update_person_properties_returns_unavailable_when_stash_full() {
- use personhog_proto::personhog::types::v1::UpdatePersonPropertiesRequest;
- use tonic::Code;
-
+ async fn forward_or_stash_returns_unavailable_when_stash_full() {
let routing_table = Arc::new(RwLock::new(HashMap::new()));
let resolver: AddressResolver = Arc::new(|_| Some("http://localhost:50053".to_string()));
// `max_messages = 0` rejects any enqueue once the stash is open.
@@ -540,22 +373,21 @@ mod tests {
let partition = backend.partition_for_person(1, 42);
stash.begin_stash(partition).await;
- let request = UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- partition: 0, // overwritten by update_person_properties
- event_name: "test".to_string(),
- set_properties: Vec::new(),
- set_once_properties: Vec::new(),
- unset_properties: Vec::new(),
- };
-
- let result = backend.update_person_properties(request).await;
- let err = result.expect_err("stash with max_messages=0 must reject");
+ let (response, call_ms) = backend
+ .forward_or_stash(
+ "UpdatePersonProperties",
+ partition,
+ (1, 42),
+ HeaderMap::new(),
+ Bytes::new(),
+ )
+ .await;
+
assert_eq!(
- err.code(),
- Code::Unavailable,
+ response.headers().get("grpc-status").unwrap(),
+ &format!("{}", Code::Unavailable as i32),
"rejection must surface as UNAVAILABLE so callers retry"
);
+ assert!(call_ms.is_none(), "no forward happened, so no call time");
}
}
diff --git a/rust/personhog-router/src/backend/mod.rs b/rust/personhog-router/src/backend/mod.rs
index 94a2cd3b885f..79c3afc4cfcd 100644
--- a/rust/personhog-router/src/backend/mod.rs
+++ b/rust/personhog-router/src/backend/mod.rs
@@ -7,21 +7,3 @@ mod stash;
pub use leader::{AddressResolver, LeaderBackend, LeaderBackendConfig};
pub use replica::{ReplicaBackend, ReplicaDnsConfig};
pub use stash::{StashDecision, StashTable, StashedRequest};
-
-use async_trait::async_trait;
-use personhog_proto::personhog::types::v1::{
- GetPersonRequest, GetPersonResponse, UpdatePersonPropertiesRequest,
- UpdatePersonPropertiesResponse,
-};
-use tonic::Status;
-
-/// Trait for leader-specific operations: strong-consistency reads and writes.
-/// Only the leader backend implements this (partition-aware routing to leader pods).
-#[async_trait]
-pub trait LeaderOps: Send + Sync {
- async fn get_person(&self, request: GetPersonRequest) -> Result<GetPersonResponse, Status>;
- async fn update_person_properties(
- &self,
- request: UpdatePersonPropertiesRequest,
- ) -> Result<UpdatePersonPropertiesResponse, Status>;
-}
diff --git a/rust/personhog-router/src/backend/stash.rs b/rust/personhog-router/src/backend/stash.rs
index b1c8907cc951..c90c7da72c12 100644
--- a/rust/personhog-router/src/backend/stash.rs
+++ b/rust/personhog-router/src/backend/stash.rs
@@ -17,12 +17,11 @@ use std::collections::VecDeque;
use std::sync::Arc;
use std::time::Instant;
+use bytes::Bytes;
use dashmap::DashMap;
-use personhog_proto::personhog::types::v1::{
- UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
-};
+use http::HeaderMap;
use tokio::sync::{oneshot, Mutex};
-use tonic::Status;
+use tonic::body::BoxBody;
/// Fixed per-request overhead estimate that approximates the bookkeeping
/// cost of holding a request in the queue (struct fields, oneshot
@@ -48,25 +47,26 @@ impl RejectCause {
}
}
-/// Approximate the memory footprint of a stashed request. Used to
-/// enforce the byte-based stash bound. Sums the variable-size fields
-/// plus a fixed overhead estimate; doesn't attempt exact proto-encoded
-/// sizing because we only need an order-of-magnitude bound, and
-/// approximate counting is cheaper.
-fn approximate_size(req: &UpdatePersonPropertiesRequest) -> usize {
- PER_REQUEST_OVERHEAD
- + req.event_name.len()
- + req.set_properties.len()
- + req.set_once_properties.len()
- + req.unset_properties.iter().map(|s| s.len()).sum::<usize>()
+/// Approximate the memory footprint of a stashed request — the raw frame
+/// plus a fixed per-entry overhead estimate. Used to enforce the
+/// byte-based stash bound; an order-of-magnitude bound is enough, so this
+/// doesn't attempt exact accounting of the headers map.
+fn approximate_size(frame: &Bytes) -> usize {
+ PER_REQUEST_OVERHEAD + frame.len()
}
-/// A request held in the stash along with the channel used to deliver its
-/// response back to the original caller.
+/// A raw write held in the stash along with everything needed to replay it
+/// to the new owner and return the response to the original caller.
pub struct StashedRequest {
- pub request: UpdatePersonPropertiesRequest,
- pub client_name: Option<String>,
- pub reply: oneshot::Sender<Result<UpdatePersonPropertiesResponse, Status>>,
+ /// The raw gRPC request frame, forwarded verbatim on replay.
+ pub frame: Bytes,
+ /// The client's request headers, forwarded verbatim (the router stamps
+ /// `x-partition` at forward time).
+ pub headers: HeaderMap,
+ /// `(team_id, person_id)` — the leader's per-person serialization key,
+ /// used to preserve per-key ordering during drain.
+ pub key: (i64, i64),
+ pub reply: oneshot::Sender<http::Response<BoxBody>>,
/// Wall-clock time the request was enqueued. Used to record stash-wait
/// histograms when drain forwards the request, giving operators
/// visibility into how long callers spent parked during a handoff.
@@ -122,7 +122,7 @@ impl PartitionStash {
/// stash is full (either too many messages or too many bytes).
pub enum StashDecision {
Forward,
- Stashed(oneshot::Receiver<Result<UpdatePersonPropertiesResponse, Status>>),
+ Stashed(oneshot::Receiver<http::Response<BoxBody>>),
Rejected,
}
@@ -178,11 +178,16 @@ impl StashTable {
/// Enqueue a request if the partition is frozen; otherwise return
/// `Forward` to signal the caller should route normally.
+ /// Takes the frame and headers by reference and clones them only when
+ /// the request actually parks — the steady state (no handoff in
+ /// progress) returns `Forward` from the dashmap miss without copying
+ /// anything.
pub async fn enqueue_or_forward(
&self,
partition: u32,
- request: UpdatePersonPropertiesRequest,
- client_name: Option<String>,
+ frame: &Bytes,
+ headers: &HeaderMap,
+ key: (i64, i64),
) -> StashDecision {
let stash = match self.inner.get(&partition) {
Some(entry) => Arc::clone(entry.value()),
@@ -197,7 +202,7 @@ impl StashTable {
return StashDecision::Forward;
};
- let request_size = approximate_size(&request);
+ let request_size = approximate_size(frame);
if queue.requests.len() >= stash.max_messages {
metrics::counter!(
@@ -218,8 +223,9 @@ impl StashTable {
let (tx, rx) = oneshot::channel();
queue.requests.push_back(StashedRequest {
- request,
- client_name,
+ frame: frame.clone(),
+ headers: headers.clone(),
+ key,
reply: tx,
enqueued_at: Instant::now(),
});
@@ -305,6 +311,8 @@ impl StashTable {
#[cfg(test)]
mod tests {
use super::*;
+ use http::HeaderValue;
+ use http_body_util::{BodyExt, Empty};
/// Collect drained requests into a `Vec` via the forward-batch
/// closure. Mirrors the original return-VecDeque API for tests
@@ -332,37 +340,47 @@ mod tests {
.unwrap()
}
- fn mk_request(team_id: i64, person_id: i64) -> UpdatePersonPropertiesRequest {
- UpdatePersonPropertiesRequest {
- team_id,
- person_id,
- partition: 0,
- event_name: "test".to_string(),
- set_properties: Vec::new(),
- set_once_properties: Vec::new(),
- unset_properties: Vec::new(),
- }
+ /// Enqueue a minimal stashed write for `(team_id = 1, person_id)`.
+ async fn enqueue(table: &StashTable, partition: u32, person_id: i64) -> StashDecision {
+ table
+ .enqueue_or_forward(
+ partition,
+ &Bytes::from_static(b"x"),
+ &HeaderMap::new(),
+ (1, person_id),
+ )
+ .await
}
- fn mk_request_with_payload(
+ /// Enqueue a stashed write whose frame is `payload` bytes, exercising
+ /// the byte-based stash bound.
+ async fn enqueue_sized(
+ table: &StashTable,
+ partition: u32,
person_id: i64,
- payload_size: usize,
- ) -> UpdatePersonPropertiesRequest {
- UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id,
- partition: 0,
- event_name: "test".to_string(),
- set_properties: vec![0u8; payload_size],
- set_once_properties: Vec::new(),
- unset_properties: Vec::new(),
- }
+ payload: usize,
+ ) -> StashDecision {
+ table
+ .enqueue_or_forward(
+ partition,
+ &Bytes::from(vec![0u8; payload]),
+ &HeaderMap::new(),
+ (1, person_id),
+ )
+ .await
+ }
+
+ /// A trivial gRPC response for exercising the reply channel.
+ fn test_response() -> http::Response<BoxBody> {
+ http::Response::new(BoxBody::new(
+ Empty::<Bytes>::new().map_err(|never| match never {}),
+ ))
}
#[tokio::test]
async fn forward_when_not_frozen() {
let table = StashTable::with_bounds(usize::MAX, usize::MAX);
- match table.enqueue_or_forward(0, mk_request(1, 1), None).await {
+ match enqueue(&table, 0, 1).await {
StashDecision::Forward => {}
_ => panic!("expected Forward"),
}
@@ -373,22 +391,22 @@ mod tests {
let table = StashTable::with_bounds(usize::MAX, usize::MAX);
table.begin_stash(0).await;
- let _rx1 = match table.enqueue_or_forward(0, mk_request(1, 1), None).await {
+ let _rx1 = match enqueue(&table, 0, 1).await {
StashDecision::Stashed(rx) => rx,
_ => panic!("expected Stashed"),
};
- let _rx2 = match table.enqueue_or_forward(0, mk_request(1, 2), None).await {
+ let _rx2 = match enqueue(&table, 0, 2).await {
StashDecision::Stashed(rx) => rx,
_ => panic!("expected Stashed"),
};
let drained = drain_to_vec(&table, 0).await;
assert_eq!(drained.len(), 2);
- let ids: Vec<i64> = drained.iter().map(|s| s.request.person_id).collect();
+ let ids: Vec<i64> = drained.iter().map(|s| s.key.1).collect();
assert_eq!(ids, vec![1, 2]);
// After drain, new requests forward.
- match table.enqueue_or_forward(0, mk_request(1, 3), None).await {
+ match enqueue(&table, 0, 3).await {
StashDecision::Forward => {}
_ => panic!("expected Forward after drain"),
}
@@ -419,7 +437,7 @@ mod tests {
async fn drain_then_begin_stash_starts_fresh() {
let table = StashTable::with_bounds(usize::MAX, usize::MAX);
table.begin_stash(0).await;
- let _rx = match table.enqueue_or_forward(0, mk_request(1, 1), None).await {
+ let _rx = match enqueue(&table, 0, 1).await {
StashDecision::Stashed(rx) => rx,
_ => panic!("expected Stashed"),
};
@@ -429,7 +447,7 @@ mod tests {
// New handoff begins
table.begin_stash(0).await;
// Fresh queue; brand-new requests stash, not forward
- match table.enqueue_or_forward(0, mk_request(1, 2), None).await {
+ match enqueue(&table, 0, 2).await {
StashDecision::Stashed(_) => {}
_ => panic!("expected Stashed for fresh handoff"),
}
@@ -441,15 +459,15 @@ mod tests {
table.begin_stash(0).await;
assert!(matches!(
- table.enqueue_or_forward(0, mk_request(1, 1), None).await,
+ enqueue(&table, 0, 1).await,
StashDecision::Stashed(_)
));
assert!(matches!(
- table.enqueue_or_forward(0, mk_request(1, 2), None).await,
+ enqueue(&table, 0, 2).await,
StashDecision::Stashed(_)
));
assert!(matches!(
- table.enqueue_or_forward(0, mk_request(1, 3), None).await,
+ enqueue(&table, 0, 3).await,
StashDecision::Rejected
));
}
@@ -462,21 +480,15 @@ mod tests {
table.begin_stash(0).await;
assert!(matches!(
- table
- .enqueue_or_forward(0, mk_request_with_payload(1, 2 * 1024), None)
- .await,
+ enqueue_sized(&table, 0, 1, 2 * 1024).await,
StashDecision::Stashed(_)
));
assert!(matches!(
- table
- .enqueue_or_forward(0, mk_request_with_payload(2, 2 * 1024), None)
- .await,
+ enqueue_sized(&table, 0, 2, 2 * 1024).await,
StashDecision::Stashed(_)
));
assert!(matches!(
- table
- .enqueue_or_forward(0, mk_request_with_payload(3, 2 * 1024), None)
- .await,
+ enqueue_sized(&table, 0, 3, 2 * 1024).await,
StashDecision::Rejected
));
}
@@ -489,12 +501,12 @@ mod tests {
table.begin_stash(0).await;
assert!(matches!(
- table.enqueue_or_forward(0, mk_request(1, 1), None).await,
+ enqueue(&table, 0, 1).await,
StashDecision::Stashed(_)
));
// Second message rejected on count even though bytes are nowhere near.
assert!(matches!(
- table.enqueue_or_forward(0, mk_request(1, 2), None).await,
+ enqueue(&table, 0, 2).await,
StashDecision::Rejected
));
}
@@ -506,11 +518,11 @@ mod tests {
// p0 stashes, p1 forwards
assert!(matches!(
- table.enqueue_or_forward(0, mk_request(1, 1), None).await,
+ enqueue(&table, 0, 1).await,
StashDecision::Stashed(_)
));
assert!(matches!(
- table.enqueue_or_forward(1, mk_request(1, 1), None).await,
+ enqueue(&table, 1, 1).await,
StashDecision::Forward
));
}
@@ -532,11 +544,9 @@ mod tests {
let mut handles = Vec::with_capacity(ENQUEUERS);
for i in 0..ENQUEUERS {
let table = table.clone();
- handles.push(tokio::spawn(async move {
- table
- .enqueue_or_forward(0, mk_request(1, i as i64), None)
- .await
- }));
+ handles.push(tokio::spawn(
+ async move { enqueue(&table, 0, i as i64).await },
+ ));
}
// Race the drain against the in-flight enqueues.
@@ -583,23 +593,23 @@ mod tests {
let table = StashTable::with_bounds(usize::MAX, usize::MAX);
table.begin_stash(0).await;
- let rx = match table.enqueue_or_forward(0, mk_request(1, 1), None).await {
+ let rx = match enqueue(&table, 0, 1).await {
StashDecision::Stashed(rx) => rx,
_ => panic!("expected Stashed"),
};
let mut drained = drain_to_vec(&table, 0).await;
let req = drained.remove(0);
- let response = UpdatePersonPropertiesResponse {
- person: None,
- updated: true,
- };
+ let mut response = test_response();
+ response
+ .headers_mut()
+ .insert("x-test", HeaderValue::from_static("ok"));
req.reply
- .send(Ok(response.clone()))
+ .send(response)
.expect("send must succeed when receiver is alive");
let received = rx.await.expect("receiver must observe sender");
- assert_eq!(received.unwrap(), response);
+ assert_eq!(received.headers().get("x-test").unwrap(), "ok");
}
/// If the original caller dropped its receiver (e.g. the gRPC client
@@ -611,7 +621,7 @@ mod tests {
let table = StashTable::with_bounds(usize::MAX, usize::MAX);
table.begin_stash(0).await;
- let rx = match table.enqueue_or_forward(0, mk_request(1, 1), None).await {
+ let rx = match enqueue(&table, 0, 1).await {
StashDecision::Stashed(rx) => rx,
_ => panic!("expected Stashed"),
};
@@ -619,12 +629,8 @@ mod tests {
let mut drained = drain_to_vec(&table, 0).await;
let req = drained.remove(0);
- let response = UpdatePersonPropertiesResponse {
- person: None,
- updated: false,
- };
assert!(
- req.reply.send(Ok(response)).is_err(),
+ req.reply.send(test_response()).is_err(),
"send must return Err after the receiver is dropped"
);
}
@@ -674,7 +680,7 @@ mod tests {
// outcome here; what we *don't* accept is a non-empty
// drained queue that was just initialized by begin_stash on
// an orphaned Arc, which the tombstone prevents.
- let outcome = table.enqueue_or_forward(0, mk_request(1, 1), None).await;
+ let outcome = enqueue(&table, 0, 1).await;
match outcome {
StashDecision::Stashed(_) => {
// Fresh dashmap entry exists — begin_stash set it up correctly.
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index 6c88ee894b5e..c3e3411b4a24 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -143,14 +143,9 @@ pub struct Config {
#[envconfig(default = "10")]
pub backend_keepalive_timeout_secs: u64,
- /// Maximum gRPC message size to encode (send), in bytes.
- /// Applied to the router's gRPC server and its backend clients (replica, leader).
- /// Defaults to 128 MiB.
- #[envconfig(default = "134217728")]
- pub grpc_max_send_message_size: usize,
-
- /// Maximum gRPC message size to decode (receive), in bytes.
- /// Applied to the router's gRPC server and its backend clients (replica, leader).
+ /// Maximum request body size the proxy will collect before forwarding,
+ /// in bytes. Oversized requests are rejected with RESOURCE_EXHAUSTED.
+ /// Responses stream through unbounded (see `response_size_warn_bytes`).
#[envconfig(default = "134217728")]
pub grpc_max_recv_message_size: usize,
diff --git a/rust/personhog-router/src/grpc_http.rs b/rust/personhog-router/src/grpc_http.rs
new file mode 100644
index 000000000000..7d576328c752
--- /dev/null
+++ b/rust/personhog-router/src/grpc_http.rs
@@ -0,0 +1,107 @@
+//! Shared gRPC-over-HTTP response helpers used by the proxy, the leader
+//! backend, and the stash handler to construct error responses directly,
+//! without going through a tonic codec.
+
+use bytes::Bytes;
+use http::HeaderValue;
+use http_body_util::{BodyExt, Empty};
+use tonic::body::BoxBody;
+use tonic::Code;
+
+/// Build a gRPC error response carrying `code` and `message` in the
+/// `grpc-status`/`grpc-message` headers with an empty body.
+pub(crate) fn grpc_error_response(code: Code, message: &str) -> http::Response<BoxBody> {
+ let body = BoxBody::new(Empty::<Bytes>::new().map_err(|never| match never {}));
+ let mut response = http::Response::new(body);
+ response
+ .headers_mut()
+ .insert("content-type", HeaderValue::from_static("application/grpc"));
+ response
+ .headers_mut()
+ .insert("grpc-status", HeaderValue::from(code as i32));
+ if !message.is_empty() {
+ let encoded = percent_encode_grpc(message);
+ if let Ok(val) = encoded.parse::<HeaderValue>() {
+ response.headers_mut().insert("grpc-message", val);
+ }
+ }
+ response
+}
+
+/// Whether a response carries a non-OK `grpc-status` in its HTTP headers.
+/// gRPC errors are trailers-only responses — a single HEADERS frame — so
+/// their status is visible here without polling the body; a successful
+/// response carries its status in the trailers and reads as not-an-error.
+pub(crate) fn is_grpc_error_response(response: &http::Response<BoxBody>) -> bool {
+ response
+ .headers()
+ .get("grpc-status")
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|s| s != "0")
+}
+
+/// Percent-encode a gRPC status message so it is safe to carry in the
+/// ASCII-only `grpc-message` header.
+fn percent_encode_grpc(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for b in s.bytes() {
+ match b {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
+ out.push(b as char);
+ }
+ _ => {
+ const HEX: &[u8; 16] = b"0123456789ABCDEF";
+ out.push('%');
+ out.push(HEX[(b >> 4) as usize] as char);
+ out.push(HEX[(b & 0xf) as usize] as char);
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// An error response is flagged by `is_grpc_error_response` while an
+ /// OK status is not — this drives the proxy's error counter and the
+ /// stash drain's outcome label.
+ #[test]
+ fn grpc_status_classification() {
+ assert!(!is_grpc_error_response(&grpc_error_response(Code::Ok, "")));
+ assert!(is_grpc_error_response(&grpc_error_response(
+ Code::NotFound,
+ "not found"
+ )));
+ }
+
+ #[test]
+ fn grpc_error_response_sets_status_and_message() {
+ let response = grpc_error_response(Code::NotFound, "person not found");
+ assert_eq!(
+ response.headers().get("grpc-status").unwrap(),
+ &format!("{}", Code::NotFound as i32),
+ );
+ let msg = response
+ .headers()
+ .get("grpc-message")
+ .unwrap()
+ .to_str()
+ .unwrap();
+ assert!(msg.contains("person"));
+ }
+
+ #[test]
+ fn percent_encode_grpc_preserves_safe_chars() {
+ assert_eq!(percent_encode_grpc("hello"), "hello");
+ assert_eq!(percent_encode_grpc("a-b_c.d~e"), "a-b_c.d~e");
+ }
+
+ #[test]
+ fn percent_encode_grpc_encodes_special_chars() {
+ assert_eq!(percent_encode_grpc("hello world"), "hello%20world");
+ assert_eq!(percent_encode_grpc("a/b"), "a%2Fb");
+ assert_eq!(percent_encode_grpc("a:b"), "a%3Ab");
+ }
+}
diff --git a/rust/personhog-router/src/lib.rs b/rust/personhog-router/src/lib.rs
index 55984716370f..0bf1f6c36240 100644
--- a/rust/personhog-router/src/lib.rs
+++ b/rust/personhog-router/src/lib.rs
@@ -1,4 +1,5 @@
pub mod backend;
pub mod config;
+pub mod grpc_http;
pub mod proxy;
pub mod stash_handler;
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index cf46b65ddd28..55ec18f017fa 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -263,8 +263,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
num_partitions,
timeout: config.backend_timeout(),
retry_config: config.retry_config(),
- max_send_message_size: config.grpc_max_send_message_size,
- max_recv_message_size: config.grpc_max_recv_message_size,
},
StashTable::with_bounds(
config.stash_max_messages_per_partition,
diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rs
index 742b06a7cc9e..4e7e3e8e52a0 100644
--- a/rust/personhog-router/src/proxy.rs
+++ b/rust/personhog-router/src/proxy.rs
@@ -2,26 +2,24 @@ use std::convert::Infallible;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
-use std::time::Instant;
+use std::time::{Duration, Instant};
use bytes::Bytes;
-use http::{HeaderMap, HeaderValue};
use http_body::Frame;
-use http_body_util::{BodyExt, Empty, Full};
+use http_body_util::{BodyExt, Full};
use metrics::{counter, histogram};
use personhog_common::grpc::{
current_caller_tag, current_client_name, ClientInFlightGuard, GZIP_OVERHEAD_HEADER,
PROCESSING_TIME_HEADER,
};
-use personhog_proto::personhog::types::v1::{GetPersonRequest, UpdatePersonPropertiesRequest};
-use prost::Message;
use rand::Rng;
use tonic::body::BoxBody;
use tonic::Code;
use tower::{Service, ServiceExt};
-use crate::backend::{LeaderBackend, LeaderOps, ReplicaBackend};
+use crate::backend::{LeaderBackend, ReplicaBackend};
use crate::config::RetryConfig;
+use crate::grpc_http::{grpc_error_response, is_grpc_error_response};
const SERVICE_PREFIX: &str = "/personhog.service.v1.PersonHogService/";
const REPLICA_PREFIX: &str = "/personhog.replica.v1.PersonHogReplica/";
@@ -157,11 +155,12 @@ impl RawProxyInner {
let start = Instant::now();
let (mut response, backend, channel_call_ms) = match method_name {
- "UpdatePersonProperties" => (
- self.handle_update_person_properties(req).await,
- "leader",
- None,
- ),
+ "UpdatePersonProperties" => {
+ let (resp, call_ms) = self
+ .raw_proxy_to_leader(req, "UpdatePersonProperties", true)
+ .await;
+ (resp, "leader", call_ms)
+ }
"GetPerson" => {
let is_strong = req
.headers()
@@ -170,7 +169,8 @@ impl RawProxyInner {
== Some("strong");
if is_strong {
- (self.handle_get_person_strong(req).await, "leader", None)
+ let (resp, call_ms) = self.raw_proxy_to_leader(req, "GetPerson", false).await;
+ (resp, "leader", call_ms)
} else {
let (resp, call_ms) = self.raw_proxy_to_replica(req, method.clone()).await;
(resp, "replica", call_ms)
@@ -317,18 +317,7 @@ impl RawProxyInner {
);
}
- counter!(
- "personhog_router_backend_retries_total",
- "method" => method.clone(),
- "status_code" => "unavailable",
- "client" => client.clone(),
- )
- .increment(1);
-
- let base = delay_ms / 2;
- let jittered = base + rand::thread_rng().gen_range(0..=base);
- tokio::time::sleep(std::time::Duration::from_millis(jittered)).await;
- delay_ms = (delay_ms * 2).min(self.retry_config.max_backoff_ms);
+ retry_backoff(&mut delay_ms, &self.retry_config, &method, &client).await;
continue;
}
};
@@ -384,18 +373,7 @@ impl RawProxyInner {
);
}
- counter!(
- "personhog_router_backend_retries_total",
- "method" => method.clone(),
- "status_code" => "unavailable",
- "client" => client.clone(),
- )
- .increment(1);
-
- let base = delay_ms / 2;
- let jittered = base + rand::thread_rng().gen_range(0..=base);
- tokio::time::sleep(std::time::Duration::from_millis(jittered)).await;
- delay_ms = (delay_ms * 2).min(self.retry_config.max_backoff_ms);
+ retry_backoff(&mut delay_ms, &self.retry_config, &method, &client).await;
}
}
}
@@ -403,185 +381,191 @@ impl RawProxyInner {
unreachable!()
}
- async fn handle_get_person_strong(
+ /// Raw-forward a leader request — a strong `GetPerson` or an
+ /// `UpdatePersonProperties` — to the owning leader pod. The routing key
+ /// arrives in the `x-team-id`/`x-person-id` headers stamped by the
+ /// client, is hashed to a partition, and the request bytes are forwarded
+ /// verbatim with the partition in the `x-partition` header. The body is
+ /// never inspected, so client-compressed request frames transit
+ /// untouched. Writes (`use_stash`) go through the per-partition stash so
+ /// they buffer correctly during a handoff; reads forward directly and
+ /// surface the channel round-trip time for the network-overhead metric.
+ async fn raw_proxy_to_leader(
&self,
req: http::Request<BoxBody>,
- ) -> http::Response<BoxBody> {
+ method: &'static str,
+ use_stash: bool,
+ ) -> (http::Response<BoxBody>, Option<f64>) {
let leader = match &self.leader {
- Some(l) => l,
+ Some(l) => l.clone(),
None => {
- return grpc_error_response(
- Code::Unimplemented,
- "leader backend not configured for this router",
+ return (
+ grpc_error_response(
+ Code::Unimplemented,
+ "leader backend not configured for this router",
+ ),
+ None,
)
}
};
- let body_bytes = match collect_request_body(req, self.max_recv_message_size).await {
- Ok(b) => b,
- Err(resp) => return resp,
- };
- let request: GetPersonRequest = match decode_grpc_message(&body_bytes) {
- Ok(m) => m,
- Err(resp) => return resp,
- };
-
- match leader.get_person(request).await {
- Ok(response) => encode_grpc_response(&response),
- Err(status) => grpc_error_response(status.code(), status.message()),
- }
- }
-
- async fn handle_update_person_properties(
- &self,
- req: http::Request<BoxBody>,
- ) -> http::Response<BoxBody> {
- let leader = match &self.leader {
- Some(l) => l,
- None => {
- return grpc_error_response(
- Code::Unimplemented,
- "leader backend not configured for this router",
- )
- }
+ // Reject requests without a routing key before paying for body
+ // collection.
+ let (team_id, person_id) = match person_key_from_headers(req.headers()) {
+ Ok(key) => key,
+ Err(resp) => return (resp, None),
};
- let body_bytes = match collect_request_body(req, self.max_recv_message_size).await {
+ let (parts, body) = req.into_parts();
+ let collect_start = Instant::now();
+ let body_bytes = match collect_body_limited(body, self.max_recv_message_size).await {
Ok(b) => b,
- Err(resp) => return resp,
- };
- let request: UpdatePersonPropertiesRequest = match decode_grpc_message(&body_bytes) {
- Ok(m) => m,
- Err(resp) => return resp,
+ Err(resp) => return (resp, None),
};
+ histogram!(
+ "personhog_router_body_collect_ms",
+ "method" => method,
+ "client" => current_client_name(),
+ )
+ .record(collect_start.elapsed().as_secs_f64() * 1000.0);
- match leader.update_person_properties(request).await {
- Ok(response) => encode_grpc_response(&response),
- Err(status) => grpc_error_response(status.code(), status.message()),
+ let partition = leader.partition_for_person(team_id, person_id);
+
+ let _in_flight = ClientInFlightGuard::new("leader");
+ if use_stash {
+ leader
+ .forward_or_stash(
+ method,
+ partition,
+ (team_id, person_id),
+ parts.headers,
+ body_bytes,
+ )
+ .await
+ } else {
+ match leader
+ .forward_raw(method, partition, &parts.headers, &body_bytes)
+ .await
+ {
+ Ok((response, call_ms)) => (response, Some(call_ms)),
+ Err(status) => (grpc_error_response(status.code(), status.message()), None),
+ }
}
}
}
// ── gRPC body helpers ──────────────────────────────────────────────────
-async fn collect_request_body(
- req: http::Request<BoxBody>,
- max_bytes: usize,
-) -> Result<Bytes, http::Response<BoxBody>> {
- let (_, body) = req.into_parts();
- collect_body_limited(body, max_bytes).await
-}
-
async fn collect_body_limited(
mut body: BoxBody,
max_bytes: usize,
) -> Result<Bytes, http::Response<BoxBody>> {
- let mut buf = Vec::new();
+ // Most unary requests arrive as a single DATA frame, which we hand on
+ // as-is without copying the payload. Only bodies that span multiple
+ // frames (large payloads split at the HTTP/2 frame size) pay for
+ // reassembly into a contiguous buffer, which the retry path needs so
+ // it can replay the request.
+ let mut first: Option<Bytes> = None;
+ let mut buf: Vec<u8> = Vec::new();
while let Some(frame_result) = body.frame().await {
let frame = frame_result.map_err(|e| {
grpc_error_response(Code::Internal, &format!("failed to read body: {e}"))
})?;
- if let Ok(data) = frame.into_data() {
- if buf.len() + data.len() > max_bytes {
- return Err(grpc_error_response(
- Code::ResourceExhausted,
- &format!("received message larger than max ({max_bytes} bytes)"),
- ));
+ let Ok(data) = frame.into_data() else {
+ continue;
+ };
+
+ let collected = first.as_ref().map_or(0, Bytes::len) + buf.len();
+ if collected + data.len() > max_bytes {
+ return Err(grpc_error_response(
+ Code::ResourceExhausted,
+ &format!("received message larger than max ({max_bytes} bytes)"),
+ ));
+ }
+
+ if first.is_none() && buf.is_empty() {
+ first = Some(data);
+ } else {
+ if let Some(f) = first.take() {
+ buf.reserve(f.len() + data.len());
+ buf.extend_from_slice(&f);
}
buf.extend_from_slice(&data);
}
}
- Ok(Bytes::from(buf))
+ Ok(match first {
+ Some(single_frame) => single_frame,
+ None => Bytes::from(buf),
+ })
}
-#[allow(clippy::result_large_err)]
-fn decode_grpc_message<M: Message + Default>(body: &Bytes) -> Result<M, http::Response<BoxBody>> {
- if body.len() < 5 {
- return Err(grpc_error_response(Code::Internal, "gRPC frame too short"));
- }
-
- if body[0] != 0 {
- return Err(grpc_error_response(
- Code::Unimplemented,
- "compressed requests not supported for typed proxy path",
- ));
- }
-
- let len = u32::from_be_bytes([body[1], body[2], body[3], body[4]]) as usize;
- if body.len() < 5 + len {
- return Err(grpc_error_response(Code::Internal, "gRPC frame truncated"));
- }
-
- M::decode(&body[5..5 + len])
- .map_err(|e| grpc_error_response(Code::Internal, &format!("proto decode error: {e}")))
-}
-
-fn encode_grpc_response<M: Message>(msg: &M) -> http::Response<BoxBody> {
- let encoded = msg.encode_to_vec();
- let mut buf = Vec::with_capacity(5 + encoded.len());
- buf.push(0); // not compressed
- buf.extend_from_slice(&(encoded.len() as u32).to_be_bytes());
- buf.extend(encoded);
-
- let mut trailers = HeaderMap::new();
- trailers.insert("grpc-status", HeaderValue::from_static("0"));
-
- let body = GrpcResponseBody {
- data: Some(Bytes::from(buf)),
- trailers: Some(trailers),
- };
-
- let mut response = http::Response::new(BoxBody::new(body));
- response
- .headers_mut()
- .insert("content-type", HeaderValue::from_static("application/grpc"));
- response
-}
-
-fn grpc_error_response(code: Code, message: &str) -> http::Response<BoxBody> {
- let body = BoxBody::new(Empty::<Bytes>::new().map_err(|never| match never {}));
- let mut response = http::Response::new(body);
- response
- .headers_mut()
- .insert("content-type", HeaderValue::from_static("application/grpc"));
- response
- .headers_mut()
- .insert("grpc-status", HeaderValue::from(code as i32));
- if !message.is_empty() {
- let encoded = percent_encode_grpc(message);
- if let Ok(val) = encoded.parse::<HeaderValue>() {
- response.headers_mut().insert("grpc-message", val);
- }
- }
- response
+/// Shared retry bookkeeping for the raw-forward paths: bump the retry
+/// counter, sleep a jittered backoff, and grow the delay toward the cap.
+async fn retry_backoff(
+ delay_ms: &mut u64,
+ retry_config: &RetryConfig,
+ method: &Arc<str>,
+ client: &Arc<str>,
+) {
+ counter!(
+ "personhog_router_backend_retries_total",
+ "method" => method.clone(),
+ "status_code" => "unavailable",
+ "client" => client.clone(),
+ )
+ .increment(1);
+
+ let base = *delay_ms / 2;
+ let jittered = base + rand::thread_rng().gen_range(0..=base);
+ tokio::time::sleep(Duration::from_millis(jittered)).await;
+ *delay_ms = (*delay_ms * 2).min(retry_config.max_backoff_ms);
}
-fn is_grpc_error_response(response: &http::Response<BoxBody>) -> bool {
- response
- .headers()
- .get("grpc-status")
- .and_then(|v| v.to_str().ok())
- .is_some_and(|s| s != "0")
+/// Routing-key headers stamped by clients on every leader-path request.
+/// The router hashes these to a partition instead of inspecting the request
+/// body; the leader independently validates them against the decoded body.
+const TEAM_ID_HEADER: &str = "x-team-id";
+const PERSON_ID_HEADER: &str = "x-person-id";
+
+/// Extract the `(team_id, person_id)` routing key from request headers.
+/// A missing or malformed header means the client predates the header
+/// contract or the request is malformed, so we fail closed rather than
+/// guess a partition.
+// `http::Response` is the error type every helper on this path returns; the
+// large variant trips `result_large_err`, but boxing here would diverge from
+// `collect_body_limited` and friends.
+#[allow(clippy::result_large_err)]
+fn person_key_from_headers(
+ headers: &http::HeaderMap,
+) -> Result<(i64, i64), http::Response<BoxBody>> {
+ let team_id = i64_header(headers, TEAM_ID_HEADER)?;
+ let person_id = i64_header(headers, PERSON_ID_HEADER)?;
+ Ok((team_id, person_id))
}
-fn percent_encode_grpc(s: &str) -> String {
- let mut out = String::with_capacity(s.len());
- for b in s.bytes() {
- match b {
- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
- out.push(b as char);
- }
- _ => {
- const HEX: &[u8; 16] = b"0123456789ABCDEF";
- out.push('%');
- out.push(HEX[(b >> 4) as usize] as char);
- out.push(HEX[(b & 0xf) as usize] as char);
- }
- }
- }
- out
+#[allow(clippy::result_large_err)]
+fn i64_header(
+ headers: &http::HeaderMap,
+ name: &'static str,
+) -> Result<i64, http::Response<BoxBody>> {
+ let value = headers.get(name).ok_or_else(|| {
+ grpc_error_response(
+ Code::InvalidArgument,
+ &format!("missing {name} header required for leader routing"),
+ )
+ })?;
+ value
+ .to_str()
+ .ok()
+ .and_then(|v| v.parse::<i64>().ok())
+ .ok_or_else(|| {
+ grpc_error_response(
+ Code::InvalidArgument,
+ &format!("{name} header is not a valid integer"),
+ )
+ })
}
/// Response body wrapper that counts bytes from DATA frames and records
@@ -661,35 +645,11 @@ impl Drop for ByteCountedBody {
}
}
-/// HTTP body that yields one data frame followed by one trailers frame.
-/// Used for constructing gRPC responses from typed leader calls.
-struct GrpcResponseBody {
- data: Option<Bytes>,
- trailers: Option<HeaderMap>,
-}
-
-impl http_body::Body for GrpcResponseBody {
- type Data = Bytes;
- type Error = tonic::Status;
-
- fn poll_frame(
- self: Pin<&mut Self>,
- _cx: &mut Context<'_>,
- ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
- let this = self.get_mut();
- if let Some(data) = this.data.take() {
- Poll::Ready(Some(Ok(Frame::data(data))))
- } else if let Some(trailers) = this.trailers.take() {
- Poll::Ready(Some(Ok(Frame::trailers(trailers))))
- } else {
- Poll::Ready(None)
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
+ use futures::stream;
+ use http_body_util::{Empty, StreamBody};
#[test]
fn known_method_lookup() {
@@ -739,97 +699,45 @@ mod tests {
);
}
+ /// Well-formed routing-key headers yield the `(team_id, person_id)`
+ /// pair the router hashes for partition placement.
#[test]
- fn decode_grpc_message_roundtrip() {
- let msg = GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: None,
- };
- let encoded = msg.encode_to_vec();
- let mut buf = Vec::with_capacity(5 + encoded.len());
- buf.push(0);
- buf.extend_from_slice(&(encoded.len() as u32).to_be_bytes());
- buf.extend(encoded);
-
- let decoded: GetPersonRequest = decode_grpc_message(&Bytes::from(buf)).unwrap();
- assert_eq!(decoded.team_id, 1);
- assert_eq!(decoded.person_id, 42);
- }
-
- #[test]
- fn decode_grpc_message_too_short() {
- let result: Result<GetPersonRequest, _> =
- decode_grpc_message(&Bytes::from_static(&[0, 0, 0, 0]));
- assert!(result.is_err());
- }
-
- #[test]
- fn decode_grpc_message_compressed_rejected() {
- let result: Result<GetPersonRequest, _> =
- decode_grpc_message(&Bytes::from_static(&[1, 0, 0, 0, 0]));
- assert!(result.is_err());
- }
-
- #[test]
- fn decode_grpc_message_truncated() {
- let result: Result<GetPersonRequest, _> =
- decode_grpc_message(&Bytes::from_static(&[0, 0, 0, 0, 10]));
- assert!(result.is_err());
- }
-
- #[test]
- fn encode_grpc_response_has_correct_headers() {
- use personhog_proto::personhog::types::v1::GetPersonResponse;
-
- let msg = GetPersonResponse { person: None };
- let response = encode_grpc_response(&msg);
-
- assert_eq!(
- response.headers().get("content-type").unwrap(),
- "application/grpc"
- );
- }
-
- #[test]
- fn grpc_error_response_sets_status_and_message() {
- let response = grpc_error_response(Code::NotFound, "person not found");
- assert_eq!(
- response.headers().get("grpc-status").unwrap(),
- &format!("{}", Code::NotFound as i32),
- );
- let msg = response
- .headers()
- .get("grpc-message")
- .unwrap()
- .to_str()
- .unwrap();
- assert!(msg.contains("person"));
- }
+ fn person_key_from_headers_extracts_key() {
+ let mut headers = http::HeaderMap::new();
+ headers.insert(TEAM_ID_HEADER, "1".parse().unwrap());
+ headers.insert(PERSON_ID_HEADER, "42".parse().unwrap());
- #[test]
- fn grpc_error_response_ok_not_flagged_as_error() {
- let ok = grpc_error_response(Code::Ok, "");
- assert!(!is_grpc_error_response(&ok));
+ let (team_id, person_id) = person_key_from_headers(&headers).expect("valid headers");
+ assert_eq!(team_id, 1);
+ assert_eq!(person_id, 42);
}
+ /// Missing or malformed routing-key headers fail closed with
+ /// InvalidArgument — the router must never guess a partition.
#[test]
- fn grpc_error_response_flagged_as_error() {
- let err = grpc_error_response(Code::NotFound, "not found");
- assert!(is_grpc_error_response(&err));
- }
-
- #[test]
- fn percent_encode_grpc_preserves_safe_chars() {
- assert_eq!(percent_encode_grpc("hello"), "hello");
- assert_eq!(percent_encode_grpc("a-b_c.d~e"), "a-b_c.d~e");
- }
-
- #[test]
- fn percent_encode_grpc_encodes_special_chars() {
- assert_eq!(percent_encode_grpc("hello world"), "hello%20world");
- assert_eq!(percent_encode_grpc("a/b"), "a%2Fb");
- assert_eq!(percent_encode_grpc("a:b"), "a%3Ab");
+ fn person_key_from_headers_rejects_missing_or_malformed() {
+ let cases: [(Option<&str>, Option<&str>, &str); 4] = [
+ (None, Some("42"), "missing x-team-id"),
+ (Some("1"), None, "missing x-person-id"),
+ (Some("abc"), Some("42"), "non-numeric x-team-id"),
+ (Some("1"), Some("12.5"), "non-integer x-person-id"),
+ ];
+
+ for (team, person, why) in cases {
+ let mut headers = http::HeaderMap::new();
+ if let Some(v) = team {
+ headers.insert(TEAM_ID_HEADER, v.parse().unwrap());
+ }
+ if let Some(v) = person {
+ headers.insert(PERSON_ID_HEADER, v.parse().unwrap());
+ }
+ let resp = person_key_from_headers(&headers).expect_err(&format!("must reject: {why}"));
+ assert_eq!(
+ resp.headers().get("grpc-status").unwrap(),
+ &format!("{}", Code::InvalidArgument as i32),
+ "wrong status for: {why}"
+ );
+ }
}
#[tokio::test]
@@ -861,4 +769,33 @@ mod tests {
assert!(result.is_ok());
assert!(result.unwrap().is_empty());
}
+
+ /// Build a body that yields each chunk as its own DATA frame,
+ /// exercising the multi-frame reassembly path (large payloads arrive
+ /// split at the HTTP/2 frame size).
+ fn multi_frame_body(chunks: Vec<&'static [u8]>) -> BoxBody {
+ let frames = chunks
+ .into_iter()
+ .map(|c| Ok::<_, tonic::Status>(Frame::data(Bytes::from_static(c))));
+ BoxBody::new(StreamBody::new(stream::iter(frames)))
+ }
+
+ #[tokio::test]
+ async fn collect_body_limited_reassembles_multiple_frames() {
+ let body = multi_frame_body(vec![b"hello ", b"personhog ", b"world"]);
+ let result = collect_body_limited(body, 100).await.unwrap();
+ assert_eq!(&result[..], b"hello personhog world");
+ }
+
+ #[tokio::test]
+ async fn collect_body_limited_rejects_over_limit_across_frames() {
+ // Each frame is under the limit; their sum is not.
+ let body = multi_frame_body(vec![&[0u8; 60], &[0u8; 60]]);
+ let result = collect_body_limited(body, 100).await;
+ let resp = result.unwrap_err();
+ assert_eq!(
+ resp.headers().get("grpc-status").unwrap(),
+ &format!("{}", Code::ResourceExhausted as i32),
+ );
+ }
}
diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rs
index 2bfbdc9143eb..ec9cb0ecff0a 100644
--- a/rust/personhog-router/src/stash_handler.rs
+++ b/rust/personhog-router/src/stash_handler.rs
@@ -6,9 +6,14 @@ use async_trait::async_trait;
use futures::future::join_all;
use personhog_coordination::error::Result as CoordResult;
use personhog_coordination::routing_table::StashHandler;
-use tonic::Status;
+use tonic::Code;
use crate::backend::{LeaderBackend, StashedRequest};
+use crate::grpc_http::{grpc_error_response, is_grpc_error_response};
+
+/// gRPC method name for stashed writes — the stash buffers only the write
+/// path, so every replayed frame targets `UpdatePersonProperties`.
+const UPDATE_METHOD: &str = "UpdatePersonProperties";
/// Stash handler for the router. Reacts to handoff phase transitions:
///
@@ -87,6 +92,7 @@ impl RouterStashHandler {
async fn forward_one(
leader_backend: &LeaderBackend,
max_stash_wait: Duration,
+ partition: u32,
stashed_req: StashedRequest,
) {
let waited = stashed_req.enqueued_at.elapsed();
@@ -97,10 +103,11 @@ async fn forward_one(
// Past deadline — return a definitive UNAVAILABLE so the
// client knows it must retry, instead of leaving them waiting
// for a leader response that may exceed their gRPC timeout.
- let result = Err(Status::unavailable(
+ let response = grpc_error_response(
+ Code::Unavailable,
"stash wait exceeded; retry through new owner",
- ));
- if stashed_req.reply.send(result).is_err() {
+ );
+ if stashed_req.reply.send(response).is_err() {
metrics::counter!("personhog_router_stash_dropped_total").increment(1);
}
metrics::counter!(
@@ -111,21 +118,40 @@ async fn forward_one(
return;
}
- // Bypass the stash hook on the way to the leader — the dashmap
- // entry for this partition is still present (drain only evicts it
- // when the queue is observed empty under the lock), so the
- // normal `update_person_properties` would re-enqueue this request
- // and stall drain progress.
- let result = leader_backend
- .update_person_properties_no_stash(stashed_req.request)
- .await;
- let outcome = if result.is_ok() { "success" } else { "error" };
+ // Forward the buffered frame straight to the new owner. The router
+ // stamps `x-partition` and the leader serializes per key, so replaying
+ // here preserves arrival order without re-entering the stash. The
+ // outcome label counts both transport failures and leader-returned
+ // gRPC errors (trailers-only responses carry their status in the
+ // headers, so no body poll is needed to classify them).
+ let (response, outcome) = match leader_backend
+ .forward_raw(
+ UPDATE_METHOD,
+ partition,
+ &stashed_req.headers,
+ &stashed_req.frame,
+ )
+ .await
+ {
+ Ok((response, _call_ms)) => {
+ let outcome = if is_grpc_error_response(&response) {
+ "error"
+ } else {
+ "success"
+ };
+ (response, outcome)
+ }
+ Err(status) => (
+ grpc_error_response(status.code(), status.message()),
+ "error",
+ ),
+ };
metrics::counter!(
"personhog_router_stash_drained_total",
"outcome" => outcome
)
.increment(1);
- if stashed_req.reply.send(result).is_err() {
+ if stashed_req.reply.send(response).is_err() {
metrics::counter!("personhog_router_stash_dropped_total").increment(1);
}
}
@@ -141,13 +167,13 @@ async fn forward_batch_by_key(
leader_backend: Arc<LeaderBackend>,
max_stash_wait: Duration,
concurrency: usize,
+ partition: u32,
batch: Vec<StashedRequest>,
) {
type Key = (i64, i64);
let mut groups: HashMap<Key, Vec<StashedRequest>> = HashMap::new();
for req in batch {
- let key = (req.request.team_id, req.request.person_id);
- groups.entry(key).or_default().push(req);
+ groups.entry(req.key).or_default().push(req);
}
let mut groups_iter = groups.into_values();
@@ -160,7 +186,7 @@ async fn forward_batch_by_key(
let leader = Arc::clone(&leader_backend);
async move {
for req in group {
- forward_one(leader.as_ref(), max_stash_wait, req).await;
+ forward_one(leader.as_ref(), max_stash_wait, partition, req).await;
}
}
});
@@ -210,7 +236,14 @@ impl StashHandler for RouterStashHandler {
let counter = Arc::clone(&counter);
async move {
let batch_size = batch.len() as u64;
- forward_batch_by_key(leader, max_stash_wait, drain_concurrency, batch).await;
+ forward_batch_by_key(
+ leader,
+ max_stash_wait,
+ drain_concurrency,
+ partition,
+ batch,
+ )
+ .await;
counter.fetch_add(batch_size, std::sync::atomic::Ordering::Relaxed);
}
})
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index 0a4a47ae16f6..15a293eb52c8 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -10,7 +10,6 @@ use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};
use personhog_proto::personhog::leader::v1::person_hog_leader_server::{
PersonHogLeader, PersonHogLeaderServer,
};
-use personhog_proto::personhog::leader::v1::LeaderGetPersonRequest;
use personhog_proto::personhog::replica::v1::person_hog_replica_server::{
PersonHogReplica, PersonHogReplicaServer,
};
@@ -490,9 +489,7 @@ pub async fn start_test_replica(service: TestReplicaService) -> SocketAddr {
tokio::spawn(async move {
Server::builder()
.add_service(
- PersonHogReplicaServer::new(service)
- .accept_compressed(CompressionEncoding::Zstd)
- .send_compressed(CompressionEncoding::Zstd),
+ PersonHogReplicaServer::new(service).accept_compressed(CompressionEncoding::Gzip),
)
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
.await
@@ -520,9 +517,7 @@ pub async fn start_test_replica_with_async_gzip(service: TestReplicaService) ->
..AsyncGzipConfig::default()
}))
.add_service(
- PersonHogReplicaServer::new(service)
- .accept_compressed(CompressionEncoding::Zstd)
- .send_compressed(CompressionEncoding::Zstd),
+ PersonHogReplicaServer::new(service).accept_compressed(CompressionEncoding::Gzip),
)
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
.await
@@ -546,9 +541,7 @@ pub async fn start_test_replica_with_async_gzip_disabled(
Server::builder()
.layer(AsyncGzipLayer::new(AsyncGzipConfig::default()))
.add_service(
- PersonHogReplicaServer::new(service)
- .accept_compressed(CompressionEncoding::Zstd)
- .send_compressed(CompressionEncoding::Zstd),
+ PersonHogReplicaServer::new(service).accept_compressed(CompressionEncoding::Gzip),
)
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
.await
@@ -566,13 +559,12 @@ pub async fn create_client(router_addr: SocketAddr) -> PersonHogServiceClient<Ch
PersonHogServiceClient::connect(url).await.unwrap()
}
-/// Create a client that sends Zstd-compressed requests.
+/// Create a client that sends gzip-compressed requests, matching a
+/// production client with request compression opted in.
pub async fn create_compressed_client(router_addr: SocketAddr) -> PersonHogServiceClient<Channel> {
let url = format!("http://{}", router_addr);
let channel = Channel::from_shared(url).unwrap().connect().await.unwrap();
- PersonHogServiceClient::new(channel)
- .send_compressed(CompressionEncoding::Zstd)
- .accept_compressed(CompressionEncoding::Zstd)
+ PersonHogServiceClient::new(channel).send_compressed(CompressionEncoding::Gzip)
}
/// Send a raw gRPC unary request with `grpc-accept-encoding: gzip` and return
@@ -648,7 +640,10 @@ pub fn create_test_person() -> Person {
// ============================================================
/// A simple in-memory leader service for integration tests.
-/// Stores persons keyed by (team_id, person_id), ignoring partition for lookups.
+/// Stores persons keyed by (team_id, person_id). Mirrors the real leader's
+/// `x-partition` handling — fail closed when the metadata is missing or
+/// malformed — so tests through the router prove the router actually
+/// stamps the header, not just that the body arrives intact.
pub struct TestLeaderService {
persons: DashMap<(i64, i64), Person>,
}
@@ -666,12 +661,27 @@ impl TestLeaderService {
}
}
+/// Extract the routing partition from `x-partition` metadata, matching the
+/// real leader's `partition_from_metadata` semantics.
+#[allow(clippy::result_large_err)]
+fn require_partition_metadata<T>(request: &Request<T>) -> Result<u32, Status> {
+ request
+ .metadata()
+ .get("x-partition")
+ .ok_or_else(|| Status::invalid_argument("missing x-partition metadata"))?
+ .to_str()
+ .map_err(|_| Status::invalid_argument("x-partition metadata is not valid ASCII"))?
+ .parse::<u32>()
+ .map_err(|_| Status::invalid_argument("x-partition metadata is not a valid u32"))
+}
+
#[tonic::async_trait]
impl PersonHogLeader for TestLeaderService {
async fn get_person(
&self,
- request: Request<LeaderGetPersonRequest>,
+ request: Request<GetPersonRequest>,
) -> Result<Response<GetPersonResponse>, Status> {
+ require_partition_metadata(&request)?;
let req = request.into_inner();
let person = self
.persons
@@ -691,6 +701,7 @@ impl PersonHogLeader for TestLeaderService {
&self,
request: Request<UpdatePersonPropertiesRequest>,
) -> Result<Response<UpdatePersonPropertiesResponse>, Status> {
+ require_partition_metadata(&request)?;
let req = request.into_inner();
let key = (req.team_id, req.person_id);
@@ -736,17 +747,9 @@ pub async fn start_test_leader(service: TestLeaderService) -> SocketAddr {
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
- // The production `LeaderBackend` configures its gRPC client with
- // `send_compressed(Zstd) + accept_compressed(Zstd)`, so the test
- // leader must accept (and may send) Zstd-compressed payloads to
- // mirror real wire behavior. Without this the LeaderBackend
- // forwards a Zstd-compressed body and the server returns
- // `Unimplemented: Content is compressed with zstd which isn't supported`.
Server::builder()
.add_service(
- PersonHogLeaderServer::new(service)
- .accept_compressed(CompressionEncoding::Zstd)
- .send_compressed(CompressionEncoding::Zstd),
+ PersonHogLeaderServer::new(service).accept_compressed(CompressionEncoding::Gzip),
)
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
.await
@@ -799,8 +802,6 @@ fn make_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<Lead
num_partitions,
timeout: Duration::from_secs(5),
retry_config,
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
},
StashTable::with_bounds(usize::MAX, usize::MAX),
))
diff --git a/rust/personhog-router/tests/raw_proxy_integration.rs b/rust/personhog-router/tests/raw_proxy_integration.rs
index ac9b9c0224be..121ba5084d3a 100644
--- a/rust/personhog-router/tests/raw_proxy_integration.rs
+++ b/rust/personhog-router/tests/raw_proxy_integration.rs
@@ -10,7 +10,7 @@ use common::{
use personhog_proto::personhog::types::v1::{
CheckCohortMembershipRequest, CohortMembership, DeletePersonsRequest, GetGroupsRequest,
GetPersonByDistinctIdRequest, GetPersonRequest, GetPersonResponse,
- GetPersonsByDistinctIdsInTeamRequest, Group, GroupIdentifier, Person, PersonWithDistinctIds,
+ GetPersonsByDistinctIdsInTeamRequest, Group, GroupIdentifier, Person,
UpdatePersonPropertiesRequest,
};
use tonic::Request;
@@ -25,6 +25,19 @@ fn with_consistency<T>(req: T, consistency: &str) -> Request<T> {
request
}
+/// Stamp the `x-team-id`/`x-person-id` routing-key headers the router
+/// requires on every leader-path request. Composes with `with_consistency`
+/// for strong reads.
+fn with_person_key<T>(mut request: Request<T>, team_id: i64, person_id: i64) -> Request<T> {
+ request
+ .metadata_mut()
+ .insert("x-team-id", team_id.to_string().parse().unwrap());
+ request
+ .metadata_mut()
+ .insert("x-person-id", person_id.to_string().parse().unwrap());
+ request
+}
+
// ============================================================
// 1. Replica routing — raw byte pass-through
// ============================================================
@@ -189,7 +202,7 @@ async fn raw_proxy_delete_persons_routes_to_replica() {
}
// ============================================================
-// 2. Leader routing — typed deserialization
+// 2. Leader routing — header-keyed raw passthrough
// ============================================================
#[tokio::test]
@@ -205,13 +218,17 @@ async fn raw_proxy_strong_get_person_routes_to_leader() {
let mut client = create_client(router_addr).await;
let response = client
- .get_person(with_consistency(
- GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: None,
- },
- "strong",
+ .get_person(with_person_key(
+ with_consistency(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ },
+ "strong",
+ ),
+ 1,
+ 42,
))
.await
.unwrap();
@@ -232,15 +249,19 @@ async fn raw_proxy_update_person_properties_routes_to_leader() {
let mut client = create_client(router_addr).await;
let response = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "Test User"})).unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_person_key(
+ Request::new(UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Test User"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ }),
+ 1,
+ 42,
+ ))
.await
.unwrap();
@@ -262,20 +283,76 @@ async fn raw_proxy_write_then_strong_read_roundtrip() {
let mut client = create_client(router_addr).await;
client
+ .update_person_properties(with_person_key(
+ Request::new(UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(
+ &serde_json::json!({"email": "[email protected]"}),
+ )
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ }),
+ 1,
+ 42,
+ ))
+ .await
+ .unwrap();
+
+ let response = client
+ .get_person(with_person_key(
+ with_consistency(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ },
+ "strong",
+ ),
+ 1,
+ 42,
+ ))
+ .await
+ .unwrap();
+
+ let person = response.into_inner().person.unwrap();
+ assert_eq!(person.version, test_person.version + 1);
+
+ let props: serde_json::Value = serde_json::from_slice(&person.properties).unwrap();
+ assert_eq!(props["email"], "[email protected]");
+}
+
+/// Leader-path requests without the routing-key headers fail closed with
+/// InvalidArgument — the router must never guess a partition, and the body
+/// is deliberately never inspected as a fallback.
+#[tokio::test]
+async fn raw_proxy_leader_requests_without_key_headers_rejected() {
+ let replica_service = TestReplicaService::new();
+ let leader_service = TestLeaderService::new().with_person(create_test_person());
+
+ let replica_addr = start_test_replica(replica_service).await;
+ let leader_addr = start_test_leader(leader_service).await;
+ let router_addr =
+ start_test_router_raw_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
+ let mut client = create_client(router_addr).await;
+
+ let update_result = client
.update_person_properties(UpdatePersonPropertiesRequest {
team_id: 1,
person_id: 42,
event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"email": "[email protected]"}))
- .unwrap(),
+ set_properties: vec![],
set_once_properties: vec![],
unset_properties: vec![],
- partition: 0,
})
- .await
- .unwrap();
+ .await;
+ let status = update_result.expect_err("write without key headers must be rejected");
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ assert!(status.message().contains("x-team-id"));
- let response = client
+ let read_result = client
.get_person(with_consistency(
GetPersonRequest {
team_id: 1,
@@ -284,14 +361,10 @@ async fn raw_proxy_write_then_strong_read_roundtrip() {
},
"strong",
))
- .await
- .unwrap();
-
- let person = response.into_inner().person.unwrap();
- assert_eq!(person.version, test_person.version + 1);
-
- let props: serde_json::Value = serde_json::from_slice(&person.properties).unwrap();
- assert_eq!(props["email"], "[email protected]");
+ .await;
+ let status = read_result.expect_err("strong read without key headers must be rejected");
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ assert!(status.message().contains("x-team-id"));
}
// ============================================================
@@ -339,7 +412,6 @@ async fn raw_proxy_update_person_properties_no_leader_returns_unimplemented() {
set_properties: vec![],
set_once_properties: vec![],
unset_properties: vec![],
- partition: 0,
})
.await;
@@ -349,6 +421,62 @@ async fn raw_proxy_update_person_properties_no_leader_returns_unimplemented() {
assert!(status.message().contains("leader"));
}
+/// Gzip-compressed leader requests transit the raw proxy untouched: the
+/// routing key comes from headers, so the router never needs the body
+/// bytes, and the leader's `accept_compressed(Gzip)` decodes the frame.
+/// This is the end-to-end contract that motivated the header pivot —
+/// request compression composes with raw passthrough for free.
+#[tokio::test]
+async fn raw_proxy_compressed_leader_requests_transit_untouched() {
+ let test_person = create_test_person();
+ let replica_service = TestReplicaService::new();
+ let leader_service = TestLeaderService::new().with_person(test_person.clone());
+
+ let replica_addr = start_test_replica(replica_service).await;
+ let leader_addr = start_test_leader(leader_service).await;
+ let router_addr =
+ start_test_router_raw_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
+ let mut compressed = create_compressed_client(router_addr).await;
+
+ let response = compressed
+ .update_person_properties(with_person_key(
+ Request::new(UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ // Enough payload that tonic actually compresses the frame.
+ set_properties: serde_json::to_vec(&serde_json::json!({"blob": "x".repeat(4096)}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ }),
+ 1,
+ 42,
+ ))
+ .await
+ .expect("compressed write must transit the raw proxy");
+ assert!(response.into_inner().updated);
+
+ let response = compressed
+ .get_person(with_person_key(
+ with_consistency(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ },
+ "strong",
+ ),
+ 1,
+ 42,
+ ))
+ .await
+ .expect("compressed strong read must transit the raw proxy");
+ let person = response.into_inner().person.unwrap();
+ assert_eq!(person.id, test_person.id);
+ assert_eq!(person.version, test_person.version + 1);
+}
+
// ============================================================
// 4. Request body size limits
// ============================================================
@@ -391,15 +519,18 @@ async fn raw_proxy_rejects_oversized_leader_request() {
let oversized_props = vec![0u8; 2048];
let result = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: oversized_props,
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
+ .update_person_properties(with_person_key(
+ Request::new(UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: oversized_props,
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ }),
+ 1,
+ 42,
+ ))
.await;
assert!(result.is_err());
@@ -443,8 +574,12 @@ fn complex_properties() -> Vec<u8> {
.unwrap()
}
+/// On the replica path the router forwards gzip-compressed request frames
+/// untouched (the body is never inspected there) and the replica's
+/// `accept_compressed(Gzip)` decodes them. A plain client on the same
+/// router keeps working — compression is a per-client opt-in.
#[tokio::test]
-async fn raw_proxy_compressed_request_matches_uncompressed() {
+async fn raw_proxy_compressed_replica_request_transits_untouched() {
let person = Person {
properties: complex_properties(),
..create_test_person()
@@ -462,57 +597,22 @@ async fn raw_proxy_compressed_request_matches_uncompressed() {
read_options: None,
};
- let plain_resp = plain.get_person(req()).await.unwrap().into_inner();
let compressed_resp = compressed.get_person(req()).await.unwrap().into_inner();
- assert_eq!(plain_resp, compressed_resp);
-}
+ assert_eq!(compressed_resp.person.unwrap().id, person.id);
-#[tokio::test]
-async fn raw_proxy_compressed_get_persons_by_distinct_ids() {
- let persons = vec![
- PersonWithDistinctIds {
- distinct_id: "user-1".to_string(),
- person: Some(create_test_person()),
- },
- PersonWithDistinctIds {
- distinct_id: "user-2".to_string(),
- person: None,
- },
- ];
- let replica_service = TestReplicaService::new().with_persons_by_distinct_id(persons);
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router_raw(replica_addr).await;
-
- let mut plain = create_client(router_addr).await;
- let mut compressed = create_compressed_client(router_addr).await;
-
- let req = || GetPersonsByDistinctIdsInTeamRequest {
- team_id: 1,
- distinct_ids: vec!["user-1".to_string(), "user-2".to_string()],
- read_options: None,
- };
-
- let plain_resp = plain
- .get_persons_by_distinct_ids_in_team(req())
- .await
- .unwrap()
- .into_inner();
- let compressed_resp = compressed
- .get_persons_by_distinct_ids_in_team(req())
- .await
- .unwrap()
- .into_inner();
- assert_eq!(plain_resp, compressed_resp);
+ let plain_resp = plain.get_person(req()).await.unwrap().into_inner();
+ assert_eq!(plain_resp.person.unwrap().id, person.id);
}
// ============================================================
-// 6. Async gzip compression
+// 6. Async gzip response compression
//
// These tests verify the AsyncGzipLayer by making raw gRPC requests with
// `grpc-accept-encoding: gzip` and inspecting the wire format. We bypass
-// tonic's client codec because tonic's `gzip` feature is intentionally
-// disabled — our layer handles gzip instead of tonic's inline compression.
-// This matches production where the client is Django's grpcio.
+// tonic's client codec so the layer's output is observable on the wire —
+// tonic never compresses responses here (no backend calls send_compressed),
+// so any gzip frame must have come from the layer. This matches production
+// where the client is Django's grpcio.
// ============================================================
/// Decompress a gRPC frame, returning the protobuf payload.
diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rs
index 6f4453d743b1..7459978ec605 100644
--- a/rust/personhog-router/tests/stash_integration.rs
+++ b/rust/personhog-router/tests/stash_integration.rs
@@ -10,13 +10,20 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
+use bytes::Bytes;
use common::{create_test_person, start_test_leader, TestLeaderService};
+use http::HeaderMap;
+use http_body_util::BodyExt;
use personhog_coordination::routing_table::StashHandler;
-use personhog_proto::personhog::types::v1::UpdatePersonPropertiesRequest;
-use personhog_router::backend::{LeaderBackend, LeaderBackendConfig, LeaderOps, StashTable};
+use personhog_proto::personhog::types::v1::{
+ UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
+};
+use personhog_router::backend::{LeaderBackend, LeaderBackendConfig, StashTable};
use personhog_router::config::RetryConfig;
use personhog_router::stash_handler::RouterStashHandler;
+use prost::Message;
use tokio::sync::RwLock;
+use tonic::body::BoxBody;
use tonic::Code;
const NUM_PARTITIONS: u32 = 8;
@@ -65,8 +72,6 @@ async fn make_backend(leader_addr: std::net::SocketAddr, stash: StashTable) -> A
num_partitions: NUM_PARTITIONS,
timeout: Duration::from_secs(5),
retry_config: retry_config(),
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
},
stash,
))
@@ -76,7 +81,6 @@ fn mk_request(team_id: i64, person_id: i64, set_email: &str) -> UpdatePersonProp
UpdatePersonPropertiesRequest {
team_id,
person_id,
- partition: 0, // overwritten by LeaderBackend::update_person_properties
event_name: "test".to_string(),
set_properties: serde_json::to_vec(&serde_json::json!({ "email": set_email })).unwrap(),
set_once_properties: Vec::new(),
@@ -84,6 +88,66 @@ fn mk_request(team_id: i64, person_id: i64, set_email: &str) -> UpdatePersonProp
}
}
+/// Encode a typed request into a gRPC length-prefixed frame, as a client
+/// would send it over the wire.
+fn encode_frame(req: &UpdatePersonPropertiesRequest) -> Bytes {
+ let encoded = req.encode_to_vec();
+ let mut buf = Vec::with_capacity(5 + encoded.len());
+ buf.push(0); // not compressed
+ buf.extend_from_slice(&(encoded.len() as u32).to_be_bytes());
+ buf.extend(encoded);
+ Bytes::from(buf)
+}
+
+/// Drive a write through the backend's raw, stash-aware forward path,
+/// returning the router's gRPC response.
+async fn forward(
+ backend: &LeaderBackend,
+ req: UpdatePersonPropertiesRequest,
+) -> http::Response<BoxBody> {
+ let partition = backend.partition_for_person(req.team_id, req.person_id);
+ let key = (req.team_id, req.person_id);
+ let (response, _call_ms) = backend
+ .forward_or_stash(
+ "UpdatePersonProperties",
+ partition,
+ key,
+ HeaderMap::new(),
+ encode_frame(&req),
+ )
+ .await;
+ response
+}
+
+/// Decode a router response into the typed leader response on success, or
+/// its gRPC status code on error. The status lives in the response headers
+/// (router-generated errors, trailers-only leader errors) or the trailers
+/// (a normal leader response).
+async fn decode_response(
+ resp: http::Response<BoxBody>,
+) -> Result<UpdatePersonPropertiesResponse, Code> {
+ let (parts, body) = resp.into_parts();
+ let collected = body.collect().await.expect("collect leader response body");
+ let trailers = collected.trailers().cloned();
+ let data = collected.to_bytes();
+
+ let status = parts
+ .headers
+ .get("grpc-status")
+ .or_else(|| trailers.as_ref().and_then(|t| t.get("grpc-status")))
+ .and_then(|v| v.to_str().ok())
+ .and_then(|s| s.parse::<i32>().ok())
+ .unwrap_or(0);
+ if status != 0 {
+ return Err(Code::from(status));
+ }
+
+ let msg = data
+ .get(5..)
+ .expect("successful response carries a gRPC frame");
+ Ok(UpdatePersonPropertiesResponse::decode(msg).expect("decode UpdatePersonPropertiesResponse"))
+}
+
/// A request that arrives while the stash is open must park on a oneshot,
/// and a subsequent `drain_stash` must forward it to the leader and deliver
/// the leader's reply back to the original caller. This is the core contract
@@ -107,8 +171,7 @@ async fn request_during_stash_completes_after_drain() {
// Send the write. It should park inside the LeaderBackend's stash hook.
let req = mk_request(person.team_id, person.id, "[email protected]");
let backend_for_call = Arc::clone(&backend);
- let in_flight =
- tokio::spawn(async move { backend_for_call.update_person_properties(req).await });
+ let in_flight = tokio::spawn(async move { forward(&backend_for_call, req).await });
// Briefly wait so the in-flight request actually parked in the stash.
tokio::time::sleep(Duration::from_millis(50)).await;
@@ -125,11 +188,11 @@ async fn request_during_stash_completes_after_drain() {
.await
.expect("drain_stash should succeed");
- let response = tokio::time::timeout(Duration::from_secs(2), in_flight)
+ let raw = tokio::time::timeout(Duration::from_secs(2), in_flight)
.await
.expect("drain should release the parked request promptly")
- .expect("task should not panic")
- .expect("update should succeed");
+ .expect("task should not panic");
+ let response = decode_response(raw).await.expect("update should succeed");
let returned = response.person.expect("leader returned a person");
assert_eq!(returned.id, person.id);
assert!(response.updated, "leader marked the update as applied");
@@ -156,9 +219,7 @@ async fn multiple_stashed_requests_drain_in_fifo() {
for i in 0..3 {
let backend = Arc::clone(&backend);
let req = mk_request(person.team_id, person.id, &format!("v{i}@example.com"));
- joins.push(tokio::spawn(async move {
- backend.update_person_properties(req).await
- }));
+ joins.push(tokio::spawn(async move { forward(&backend, req).await }));
}
tokio::time::sleep(Duration::from_millis(50)).await;
@@ -173,11 +234,11 @@ async fn multiple_stashed_requests_drain_in_fifo() {
// (1, 2, 3) — proving FIFO is preserved end to end.
let mut versions = Vec::with_capacity(3);
for j in joins {
- let resp = tokio::time::timeout(Duration::from_secs(2), j)
+ let raw = tokio::time::timeout(Duration::from_secs(2), j)
.await
.expect("each parked request should release after drain")
- .expect("task should not panic")
- .expect("update should succeed");
+ .expect("task should not panic");
+ let resp = decode_response(raw).await.expect("update should succeed");
versions.push(resp.person.unwrap().version);
}
@@ -211,13 +272,10 @@ async fn requests_for_unstashed_partition_forward_immediately() {
.unwrap();
let req = mk_request(person.team_id, person.id, "[email protected]");
- let result = tokio::time::timeout(
- Duration::from_secs(2),
- backend.update_person_properties(req),
- )
- .await
- .expect("forward should not block");
- let response = result.expect("update should succeed");
+ let raw = tokio::time::timeout(Duration::from_secs(2), forward(&backend, req))
+ .await
+ .expect("forward should not block");
+ let response = decode_response(raw).await.expect("update should succeed");
assert!(response.updated);
}
@@ -240,17 +298,17 @@ async fn stash_full_returns_unavailable_via_backend() {
// Park the first request.
let req1 = mk_request(person.team_id, person.id, "[email protected]");
let backend1 = Arc::clone(&backend);
- let _in_flight = tokio::spawn(async move { backend1.update_person_properties(req1).await });
+ let _in_flight = tokio::spawn(async move { forward(&backend1, req1).await });
tokio::time::sleep(Duration::from_millis(50)).await;
// The second request hits the cap and is rejected.
let req2 = mk_request(person.team_id, person.id, "[email protected]");
- let err = backend
- .update_person_properties(req2)
+ let raw = forward(&backend, req2).await;
+ let code = decode_response(raw)
.await
.expect_err("second request must be rejected");
assert_eq!(
- err.code(),
+ code,
Code::Unavailable,
"rejection must surface as UNAVAILABLE so callers retry"
);
@@ -275,12 +333,12 @@ async fn back_to_back_handoffs_use_fresh_queue() {
handler.begin_stash(partition, "leader-a").await.unwrap();
let req_a = mk_request(person.team_id, person.id, "[email protected]");
let backend_a = Arc::clone(&backend);
- let pending_a = tokio::spawn(async move { backend_a.update_person_properties(req_a).await });
+ let pending_a = tokio::spawn(async move { forward(&backend_a, req_a).await });
tokio::time::sleep(Duration::from_millis(20)).await;
handler.drain_stash(partition, "leader-a").await.unwrap();
- pending_a
+ let raw_a = pending_a.await.unwrap();
+ decode_response(raw_a)
.await
- .unwrap()
.expect("first handoff's stashed request should drain successfully");
// Second handoff cycle on the same partition. Must accept a new write
@@ -289,16 +347,16 @@ async fn back_to_back_handoffs_use_fresh_queue() {
handler.begin_stash(partition, "leader-b").await.unwrap();
let req_b = mk_request(person.team_id, person.id, "[email protected]");
let backend_b = Arc::clone(&backend);
- let pending_b = tokio::spawn(async move { backend_b.update_person_properties(req_b).await });
+ let pending_b = tokio::spawn(async move { forward(&backend_b, req_b).await });
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(
!pending_b.is_finished(),
"second handoff's request must park, not forward"
);
handler.drain_stash(partition, "leader-b").await.unwrap();
- pending_b
+ let raw_b = pending_b.await.unwrap();
+ decode_response(raw_b)
.await
- .unwrap()
.expect("second handoff's stashed request should drain successfully");
}
@@ -331,7 +389,7 @@ async fn ordering_preserved_when_request_arrives_during_drain() {
// Stash request "A" with email v1.
let req_a = mk_request(person.team_id, person.id, "[email protected]");
let backend_a = Arc::clone(&backend);
- let pending_a = tokio::spawn(async move { backend_a.update_person_properties(req_a).await });
+ let pending_a = tokio::spawn(async move { forward(&backend_a, req_a).await });
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(!pending_a.is_finished(), "A must be parked in stash");
@@ -352,12 +410,16 @@ async fn ordering_preserved_when_request_arrives_during_drain() {
tokio::time::sleep(Duration::from_millis(5)).await;
let req_b = mk_request(person.team_id, person.id, "[email protected]");
let backend_b = Arc::clone(&backend);
- let pending_b = tokio::spawn(async move { backend_b.update_person_properties(req_b).await });
+ let pending_b = tokio::spawn(async move { forward(&backend_b, req_b).await });
drain_task.await.unwrap();
- let resp_a = pending_a.await.unwrap().expect("A should succeed");
- let resp_b = pending_b.await.unwrap().expect("B should succeed");
+ let resp_a = decode_response(pending_a.await.unwrap())
+ .await
+ .expect("A should succeed");
+ let resp_b = decode_response(pending_b.await.unwrap())
+ .await
+ .expect("B should succeed");
let initial = person.version;
assert_eq!(
@@ -397,16 +459,18 @@ async fn stash_wait_exceeded_returns_unavailable() {
let req = mk_request(person.team_id, person.id, "[email protected]");
let backend_for_call = Arc::clone(&backend);
- let pending = tokio::spawn(async move { backend_for_call.update_person_properties(req).await });
+ let pending = tokio::spawn(async move { forward(&backend_for_call, req).await });
// Wait long enough that the stashed request is past its deadline.
tokio::time::sleep(Duration::from_millis(100)).await;
handler.drain_stash(partition, "leader-new").await.unwrap();
- let result = pending.await.unwrap();
- let err = result.expect_err("drain must fail-fast past-deadline requests");
+ let raw = pending.await.unwrap();
+ let code = decode_response(raw)
+ .await
+ .expect_err("drain must fail-fast past-deadline requests");
assert_eq!(
- err.code(),
+ code,
Code::Unavailable,
"past-deadline drained requests must surface as UNAVAILABLE"
);
@@ -439,9 +503,7 @@ async fn drain_converges_with_concurrent_arrivals() {
for _ in 0..5 {
let backend = Arc::clone(&backend);
let req = mk_request(person.team_id, person.id, "[email protected]");
- pending.push(tokio::spawn(async move {
- backend.update_person_properties(req).await
- }));
+ pending.push(tokio::spawn(async move { forward(&backend, req).await }));
}
tokio::time::sleep(Duration::from_millis(20)).await;
@@ -466,9 +528,7 @@ async fn drain_converges_with_concurrent_arrivals() {
arrival_pending_for_task
.lock()
.unwrap()
- .push(tokio::spawn(async move {
- backend.update_person_properties(req).await
- }));
+ .push(tokio::spawn(async move { forward(&backend, req).await }));
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
@@ -480,9 +540,8 @@ async fn drain_converges_with_concurrent_arrivals() {
arrival_task.await.unwrap();
// Every spawned request — pre-stashed and during-drain — must
- // produce a definitive result (success or UNAVAILABLE). We don't
- // care which; the point is that drain converged and every parked
- // future was released, not that any specific outcome held.
+ // produce a definitive result. We don't care which; the point is
+ // that drain converged and every parked future was released.
for h in pending {
drop(h.await.unwrap());
}