: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement us_census import source (#72634)
Tom Owersd9c317d19253
diff --git a/frontend/public/services/us_census.svg b/frontend/public/services/us_census.svgnew file mode 100644index 000000000000..0c857b388b57--- /dev/null+++ b/frontend/public/services/us_census.svg@@ -0,0 +1,294 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<!-- Generator: Adobe Illustrator 21.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->++<svg+ xmlns:dc="http://purl.org/dc/elements/1.1/"+ xmlns:cc="http://creativecommons.org/ns#"+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+ xmlns:svg="http://www.w3.org/2000/svg"+ xmlns="http://www.w3.org/2000/svg"+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"+ version="1.1"+ id="Layer_1"+ x="0px"+ y="0px"+ viewBox="0 0 159.28653 67.199013"+ xml:space="preserve"+ sodipodi:docname="USCENSUS_IDENTITY_SOLO_White_2in_TM.svg"+ width="159.28653"+ height="67.199013"+ inkscape:version="0.92.3 (2405546, 2018-03-11)"><metadata+ id="metadata3911"><rdf:RDF><cc:Work+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs+ id="defs3909" /><sodipodi:namedview+ pagecolor="#ffffff"+ bordercolor="#666666"+ borderopacity="1"+ objecttolerance="10"+ gridtolerance="10"+ guidetolerance="10"+ inkscape:pageopacity="0"+ inkscape:pageshadow="2"+ inkscape:window-width="1366"+ inkscape:window-height="705"+ id="namedview3907"+ showgrid="false"+ fit-margin-top="0"+ fit-margin-left="0"+ fit-margin-right="0"+ fit-margin-bottom="0"+ inkscape:zoom="4.0179165"+ inkscape:cx="56.465124"+ inkscape:cy="27.747483"+ inkscape:window-x="-8"+ inkscape:window-y="-8"+ inkscape:window-maximized="1"+ inkscape:current-layer="Layer_1" />+<style+ type="text/css"+ id="style3813">+ .Arched_x0020_Green{fill:url(#SVGID_1_);stroke:#FFFFFF;stroke-width:0.25;stroke-miterlimit:1;}+ .st0{fill:#FFFFFF;}+</style>+<linearGradient+ id="SVGID_1_"+ gradientUnits="userSpaceOnUse"+ x1="-32.579102"+ y1="133.9868"+ x2="-31.872"+ y2="133.27969">+ <stop+ offset="0"+ style="stop-color:#20AC4B"+ id="stop3815" />+ <stop+ offset="0.9831"+ style="stop-color:#19361A"+ id="stop3817" />+</linearGradient>+<rect+ id="rect3913"+ width="159.28653"+ height="67.199013"+ x="0"+ y="0"+ style="fill:#112e51;fill-opacity:1;stroke-width:0.65530246" /><g+ id="g3904"+ transform="translate(4.2310491,3.4701891)">+ <g+ id="g3830">+ <path+ class="st0"+ d="m 101.4,49 h 3.8 c 1.2,0 1.9,0.2 2.5,0.7 0.6,0.5 0.8,1.1 0.8,1.8 0,0.7 -0.2,1.3 -0.7,1.7 -0.3,0.3 -0.5,0.4 -0.9,0.5 1.4,0.4 2,1.2 2,2.6 0,1.4 -0.9,2.7 -2.7,2.8 -0.3,0 -0.7,0 -1.3,0 h -3.6 V 49 Z m 2,1.7 V 53 h 1.6 c 0.5,0 0.7,0 0.9,-0.1 0.3,-0.1 0.5,-0.6 0.5,-1 0,-0.4 -0.2,-0.8 -0.6,-1 -0.2,-0.1 -0.4,-0.1 -0.8,-0.1 h -1.6 z m 0,4 v 2.7 h 1.7 c 0.4,0 0.7,-0.1 0.9,-0.2 0.3,-0.2 0.5,-0.7 0.5,-1.2 0,-0.6 -0.3,-1.1 -0.7,-1.2 -0.2,-0.1 -0.3,-0.1 -0.8,-0.1 z"+ id="path3820"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 119.4,51.8 v 0.7 c 0.3,-0.4 0.6,-0.7 1,-0.9 0.2,-0.1 0.4,-0.1 0.6,-0.1 0.3,0 0.4,0 0.7,0.2 l -0.4,1.6 c -0.2,-0.1 -0.3,-0.1 -0.6,-0.1 -0.4,0 -0.8,0.2 -1.2,0.6 v 5.3 h -2 v -7.3 z"+ id="path3822"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 127.6,57.1 0.8,1.2 c -0.9,0.7 -1.8,1 -2.8,1 -2.1,0 -3.5,-1.5 -3.5,-3.9 0,-1.3 0.3,-2.2 0.9,-3 0.6,-0.7 1.4,-1 2.3,-1 0.9,0 1.7,0.3 2.2,0.8 0.7,0.7 1,1.7 1,3.3 0,0.2 0,0.2 0,0.5 h -4.3 v 0.1 c 0,1.2 0.6,1.8 1.6,1.8 0.6,0 1.2,-0.3 1.8,-0.8 z m -3.4,-2.5 h 2.3 v -0.1 c 0,-0.6 -0.1,-0.8 -0.2,-1.1 -0.2,-0.3 -0.5,-0.4 -0.9,-0.4 -0.8,-0.1 -1.2,0.5 -1.2,1.6 z"+ id="path3824"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 134,59.1 v -0.5 c -0.3,0.3 -0.3,0.3 -0.5,0.4 -0.4,0.3 -0.9,0.4 -1.5,0.4 -1.7,0 -2.6,-0.8 -2.6,-2.3 0,-1.8 1.2,-2.6 3.6,-2.6 0.1,0 0.2,0 0.4,0 v -0.3 c 0,-0.8 -0.2,-1.1 -0.9,-1.1 -0.6,0 -1.4,0.3 -2.2,0.8 l -0.8,-1.4 c 0.5,-0.3 0.7,-0.4 1.2,-0.6 0.7,-0.3 1.4,-0.4 2,-0.4 1.3,0 2.1,0.5 2.4,1.3 0.1,0.3 0.1,0.5 0.1,1.3 v 2.5 c 0,0 0,0.1 0,0.1 V 59 Z m -0.6,-3.2 v 0 c -1.4,0 -1.9,0.2 -1.9,1.1 0,0.6 0.4,1 0.9,1 0.4,0 0.7,-0.2 1,-0.5 z"+ id="path3826"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 141.2,59.1 v -0.5 c -0.5,0.5 -1.2,0.7 -2,0.7 -1,0 -2,-0.5 -2.2,-1.2 -0.1,-0.3 -0.2,-0.7 -0.2,-1.5 v -4.8 h 1.9 v 4.4 c 0,0.7 0,1 0.2,1.2 0.1,0.2 0.4,0.3 0.7,0.3 0.5,0 1.1,-0.3 1.2,-0.7 v -5.3 h 1.9 V 59 h -1.5 z"+ id="path3828"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <path+ class="st0"+ d="m 22.7,17.6 c -1.9,-1.3 -3.8,-1.9 -5.9,-1.9 -2.5,0 -5,1.1 -6.3,3 -1.4,2 -2.1,4.9 -2.1,8.9 0,4.7 0.4,7.4 1.5,9.3 1.5,2.5 3.9,3.9 7.1,3.9 2,0 3.8,-0.5 5.6,-1.7 0.2,-0.1 0.5,-0.3 0.7,-0.5 l 3,4.7 c -2.8,2 -5.9,2.9 -9.9,2.9 C 11.3,46.2 7.3,44.7 4.3,41.4 1.5,38.1 0,34 0,28.9 0,24.6 0.8,21.1 2.5,18.2 c 2.9,-5 8.2,-8 14.2,-8 3.4,0 6.8,0.9 8.9,2.4 z"+ id="path3832"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 46.8,38.4 2.6,3.9 c -2.9,2.4 -6,3.5 -9.5,3.5 -7.2,0 -11.9,-5.1 -11.9,-13.1 0,-4.5 0.9,-7.5 3.2,-10 2.1,-2.3 4.6,-3.4 7.9,-3.4 2.9,0 5.7,1 7.3,2.7 2.3,2.4 3.3,5.8 3.3,11 0,0.5 0,0.7 0,1.5 H 35 v 0.2 c 0,3.9 1.9,6.1 5.3,6.1 2.3,0.1 4.5,-0.7 6.5,-2.4 z M 35.1,29.8 h 7.6 v -0.3 c 0,-1.9 -0.2,-2.9 -0.8,-3.8 -0.6,-1 -1.6,-1.5 -2.9,-1.5 -2.4,0 -3.9,2 -3.9,5.6 z"+ id="path3834"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 58.7,19.6 0.6,2.8 c 1.5,-1.1 1.8,-1.3 2.9,-1.9 1.3,-0.7 3.1,-1.1 4.5,-1.1 2.8,0 5.3,1.5 6.1,3.6 0.3,0.9 0.5,2 0.5,3.6 V 45 H 66.8 V 28.7 C 66.8,25.8 66.3,25 64.6,25 63.3,25 61.5,25.9 60,27.3 V 45.1 H 53.4 V 19.6 Z"+ id="path3836"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 59.3,19.6 v 2.8 c 1.5,-1.1 1.8,-1.3 2.9,-1.9 1.3,-0.7 3.1,-1.1 4.5,-1.1 2.8,0 5.3,1.5 6.1,3.6 0.3,0.9 0.5,2 0.5,3.6 V 45 H 66.8 V 28.7 C 66.8,25.8 66.3,25 64.6,25 63.3,25 61.5,25.9 60,27.3 V 45.1 H 53.4 V 19.6 Z"+ id="path3838"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 93.9,26 c -2.5,-1.3 -4.3,-1.8 -6.2,-1.8 -1.9,0 -3.2,1 -3.2,2.5 0,1.3 0.8,2 3.2,2.6 l 3.1,0.8 c 3.1,0.8 4.1,1.7 5,2.9 0.9,1.2 1.4,2.6 1.4,4.3 0,5.2 -4.3,8.8 -10.8,8.8 -3,0 -6.3,-0.9 -9.9,-2.8 l 2.1,-5 c 2,1.2 5.5,2.9 8.4,2.9 1.9,0 3.4,-1.2 3.4,-2.9 0,-1.7 -1.2,-2.6 -3.9,-3.1 l -3,-0.5 C 81.8,34.4 79.8,33.2 78.9,32.1 78,31 77.5,29.2 77.5,27.6 c 0,-4.9 3.9,-8.2 9.7,-8.2 3.8,0 6.4,1.1 8.6,2.2 z"+ id="path3840"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 114.6,45.1 v -2.8 c -1.5,1.1 -1.8,1.3 -2.9,1.9 -1.3,0.7 -3.1,1.1 -4.5,1.1 -2.8,0 -5.3,-1.5 -6.1,-3.6 -0.3,-0.9 -0.5,-2 -0.5,-3.6 V 19.6 h 6.5 V 36 c 0,2.9 0.5,3.7 2.2,3.7 1.3,0 3.1,-0.9 4.6,-2.3 V 19.6 h 6.6 v 25.5 z"+ id="path3842"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <g+ id="g3846">+ <path+ class="st0"+ d="m 40.7,3 v 6.6 c 0,3.7 -1.8,5.7 -5,5.7 -3.3,0 -4.9,-2.1 -4.9,-5.7 V 3 H 29.3 V 1.3 h 5.1 V 3 h -1.5 v 6.8 c 0,2.4 1,3.7 2.9,3.7 2,0 2.9,-1.3 2.9,-3.6 V 3 H 37.2 V 1.3 h 5.1 V 3 h -1.6"+ id="path3844"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3850">+ <path+ class="st0"+ d="m 48.7,15.1 v -1.6 h 1.2 V 8.7 c 0,-2 -0.6,-2.5 -1.7,-2.5 -1,0 -1.7,0.5 -2.2,1.3 v 6 h 1.2 v 1.6 H 42.8 V 13.5 H 44 V 6.4 H 42.8 V 4.7 H 46 V 5.8 C 46.7,5 47.5,4.5 48.8,4.5 50.9,4.5 52,5.7 52,8.6 v 4.9 h 1.2 v 1.6 h -4.5"+ id="path3848"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3854">+ <path+ class="st0"+ d="m 56.4,3 c -0.7,0 -1.3,-0.6 -1.3,-1.3 0,-0.7 0.6,-1.3 1.3,-1.3 0.7,0 1.3,0.6 1.3,1.3 0,0.7 -0.6,1.3 -1.3,1.3 m -2.1,12.1 v -1.6 h 1.3 V 6.4 H 54.3 V 4.7 h 3.3 v 8.7 h 1.3 V 15 h -4.6 z"+ id="path3852"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3860">+ <path+ class="st0"+ d="M 65.2,14.8"+ id="path3856"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 65.2,14.8 c -0.5,0.3 -1.1,0.5 -1.9,0.5 -1.4,0 -2.2,-0.9 -2.2,-2.7 V 6.4 H 59.7 V 4.7 h 1.4 v -3 l 2,-1.1 v 4 h 2.3 v 1.6 h -2.3 v 6 c 0,1 0.3,1.2 1,1.2 0.2,0 0.4,0 0.6,-0.1 z"+ id="path3858"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3864">+ <path+ class="st0"+ d="m 74.8,10.6 h -6.4 c 0.2,1.9 0.9,2.9 2.6,2.9 1.2,0 1.9,-0.3 2.8,-1 l 0.9,1.4 c -1.1,0.9 -2.3,1.4 -3.8,1.4 -2.5,0 -4.4,-2 -4.4,-5.4 0,-3.5 1.8,-5.4 4.3,-5.4 2.8,0 4.1,2.4 4.1,5.2 0,0.4 -0.1,0.7 -0.1,0.9 M 70.6,6.2 c -1.3,0 -2,1 -2.2,2.8 h 4.4 C 72.7,7.5 72.2,6.2 70.6,6.2"+ id="path3862"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3868">+ <path+ class="st0"+ d="M 82.7,15.1 V 14 c -0.7,0.8 -1.5,1.3 -2.6,1.3 -2.2,0 -3.8,-1.6 -3.8,-5.6 0,-3.5 1.7,-5.2 3.7,-5.2 1.2,0 2,0.5 2.7,1.2 V 2.1 H 81.5 V 0.5 h 3.2 v 13 h 1.1 v 1.6 H 82.7 M 82.8,7.5 C 82.4,6.9 81.5,6.1 80.5,6.1 c -1.4,0 -2.1,1.2 -2.1,3.5 0,2.9 0.8,4 2.2,4 0.8,0 1.4,-0.4 2.2,-1.3 V 7.5 Z"+ id="path3866"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3872">+ <path+ class="st0"+ d="m 97.1,15.3 c -1.3,0 -2.3,-0.5 -3,-1.3 v 1.1 H 92.3 V 10.9 H 94 c 0.5,1.7 1.4,2.7 3.1,2.7 1.5,0 2.3,-0.7 2.3,-2.1 C 99.4,10.3 99,9.7 96.5,9 93.8,8.2 92.4,7.3 92.4,4.9 c 0,-2.3 1.6,-3.8 3.9,-3.8 1.6,0 2.5,0.6 2.9,1.3 V 1.3 H 101 V 5.5 H 99.3 C 99,3.9 98.1,2.8 96.4,2.8 c -1.5,0 -2,0.8 -2,1.8 0,1.1 0.8,1.8 2.8,2.3 2.8,0.8 4.2,1.7 4.2,4.2 0.1,2.8 -1.7,4.2 -4.3,4.2"+ id="path3870"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3876">+ <path+ class="st0"+ d="M 115.5,15.1 V 14 c -0.6,0.8 -1.6,1.3 -2.8,1.3 -1.8,0 -3.3,-0.9 -3.3,-3.4 0,-2.3 1.6,-3.4 3.8,-3.4 1,0 1.7,0.2 2.3,0.5 V 8 c 0,-1.1 -0.7,-1.8 -1.9,-1.8 -1,0 -1.8,0.2 -2.6,0.6 l -0.7,-1.4 c 0.9,-0.6 2,-0.9 3.4,-0.9 2.2,0 3.7,1.1 3.7,3.5 v 5.5 h 1.1 v 1.6 h -3 m 0,-4.6 C 115,10.2 114.4,10 113.2,10 c -1.1,0 -1.9,0.6 -1.9,1.7 0,1.3 0.6,1.8 1.8,1.8 1,0 1.9,-0.5 2.4,-1.3 z"+ id="path3874"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3880">+ <path+ class="st0"+ d="m 134.3,10.6 h -6.4 c 0.2,1.9 1,2.9 2.6,2.9 1.2,0 1.9,-0.3 2.8,-1 l 0.9,1.4 c -1.1,0.9 -2.3,1.4 -3.8,1.4 -2.5,0 -4.4,-2 -4.4,-5.4 0,-3.5 1.8,-5.4 4.3,-5.4 2.8,0 4.1,2.4 4.1,5.2 -0.1,0.4 -0.1,0.7 -0.1,0.9 m -4.2,-4.4 c -1.3,0 -2,1 -2.2,2.8 h 4.4 c -0.1,-1.5 -0.7,-2.8 -2.2,-2.8"+ id="path3878"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <g+ id="g3884">+ <path+ class="st0"+ d="m 140,15.2 c -1.2,0 -1.8,-0.3 -2.3,-1 V 15 h -1.6 v -3.2 h 1.4 c 0.6,1.2 1.3,1.8 2.4,1.8 0.8,0 1.3,-0.5 1.3,-1.2 0,-0.8 -0.3,-1.2 -1.8,-1.6 -2.5,-0.7 -3.4,-1.5 -3.4,-3.4 0,-1.5 1.1,-2.9 3.2,-2.9 0.9,0 1.6,0.2 2.2,0.8 V 4.7 H 143 V 8 h -1.4 c -0.5,-1.2 -1.1,-1.8 -2.2,-1.8 -0.9,0 -1.3,0.4 -1.3,1.1 0,0.6 0.2,1.1 1.8,1.6 2.4,0.7 3.4,1.5 3.4,3.4 -0.1,1.6 -1.3,2.9 -3.3,2.9"+ id="path3882"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <path+ class="st0"+ d="m 114.5,59.1 v -0.5 c -0.5,0.5 -1.2,0.7 -2,0.7 -1,0 -2,-0.5 -2.2,-1.2 -0.1,-0.3 -0.2,-0.7 -0.2,-1.5 v -4.8 h 1.9 v 4.4 c 0,0.7 0,1 0.2,1.2 0.1,0.2 0.4,0.3 0.7,0.3 0.5,0 1.1,-0.3 1.2,-0.7 V 51.7 H 116 V 59 h -1.5 z"+ id="path3886"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 141.2,26 c -2.5,-1.3 -4.3,-1.8 -6.2,-1.8 -1.9,0 -3.2,1 -3.2,2.5 0,1.3 0.8,2 3.2,2.6 l 3,0.7 c 3.1,0.8 4.1,1.7 5,2.9 0.9,1.2 1.4,2.6 1.4,4.3 0,5.2 -4.3,8.8 -10.8,8.8 -3,0 -6.3,-0.9 -9.9,-2.8 l 2.1,-5 c 2,1.2 5.5,2.9 8.4,2.9 1.9,0 3.4,-1.2 3.4,-2.9 0,-1.7 -1.2,-2.6 -3.9,-3.1 l -3,-0.5 C 129,34.3 127,33.1 126.1,32 c -0.9,-1.1 -1.4,-2.9 -1.4,-4.5 0,-4.9 3.9,-8.2 9.8,-8.2 3.8,0 6.4,1.1 8.6,2.2 z"+ id="path3888"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <g+ id="g3892">+ <path+ class="st0"+ d="m 3.8,52.4 h 89.8 c 1.9,0 3.4,1.5 3.4,3.4 0,1.9 -1.5,3.4 -3.4,3.4 H 3.8 c -1.9,0 -3.4,-1.5 -3.4,-3.4 0,-1.9 1.5,-3.4 3.4,-3.4 z"+ id="path3890"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+ <path+ class="st0"+ d="m 108.1,14.8 c -0.5,0.3 -1.1,0.5 -1.9,0.5 -1.4,0 -2.2,-0.9 -2.2,-2.7 V 6.4 h -1.4 V 4.7 h 1.4 v -3 l 2,-1.1 v 4 h 2.3 V 6.2 H 106 v 6 c 0,1 0.3,1.2 1,1.2 0.2,0 0.4,0 0.6,-0.1 z"+ id="path3894"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="m 124.7,14.8 c -0.5,0.3 -1.1,0.5 -1.9,0.5 -1.4,0 -2.2,-0.9 -2.2,-2.7 V 6.4 h -1.4 V 4.7 h 1.4 v -3 l 2,-1.1 v 4 h 2.3 v 1.6 h -2.3 v 6 c 0,1 0.3,1.2 1,1.2 0.2,0 0.4,0 0.6,-0.1 z"+ id="path3896"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <g+ id="g3902">+ <path+ class="st0"+ d="M 146.2,6.3 V 3.7 h -0.9 V 3.4 h 2.3 v 0.3 h -0.9 v 2.5 h -0.5 z"+ id="path3898"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ <path+ class="st0"+ d="M 148,6.3 V 3.4 h 0.6 l 0.7,2 c 0.1,0.2 0.1,0.3 0.1,0.4 0,-0.1 0.1,-0.3 0.2,-0.5 l 0.7,-2 h 0.5 v 2.9 h -0.4 V 3.9 l -0.8,2.4 h -0.3 l -0.8,-2.4 v 2.4 z"+ id="path3900"+ inkscape:connector-curvature="0"+ style="fill:#ffffff" />+ </g>+</g>+</svg>\ No newline at end of filediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 43f34821e873..36c9695d0e3b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -550,6 +550,7 @@ the row lists both.| unstructured | HTTP | requests | ✅ || upstash | HTTP | requests | ✅ || uptimerobot | HTTP | requests | ✅ |+| us_census | HTTP | requests | ✅ || usersnap | HTTP | requests + PyJWT | ✅ || uservoice | HTTP | requests | ✅ || vantage | HTTP | requests | ✅ |@@ -978,7 +979,6 @@ doesn't conflict with concurrent PRs.- twitter_ads- uppromote- uptick-- us_census- uservoice- veeqo- vespadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uscensus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uscensus.pyindex ae09fe045240..5c79f271629a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uscensus.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uscensus.py@@ -6,4 +6,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass USCensusSourceConfig(config.Config):- pass+ api_key: str+ custom_dataset: str | None = None+ custom_variables: str | None = None+ custom_geography: str | None = None+ custom_geography_filter: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/canonical_descriptions.pynew file mode 100644index 000000000000..1c571a5db567--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/canonical_descriptions.py@@ -0,0 +1,79 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_ACS_COLUMNS = {+ "NAME": "Human-readable name of the geography (e.g. state or county name).",+ "B01001_001E": "Estimated total population.",+ "B01002_001E": "Estimated median age of the population.",+ "B19013_001E": "Estimated median household income in the past 12 months (inflation-adjusted dollars).",+ "B19301_001E": "Estimated per capita income in the past 12 months (inflation-adjusted dollars).",+ "B25077_001E": "Estimated median value of owner-occupied housing units (dollars).",+ "B23025_003E": "Estimated civilian labor force (population 16 years and over).",+ "B23025_005E": "Estimated unemployed civilian labor force (population 16 years and over).",+ "B15003_022E": "Estimated population 25 years and over whose highest attainment is a bachelor's degree.",+ "state": "Two-digit state FIPS code.",+}++_DECENNIAL_COLUMNS = {+ "NAME": "Human-readable name of the geography (e.g. state or county name).",+ "P1_001N": "Total population count.",+ "H1_001N": "Total count of housing units.",+ "state": "Two-digit state FIPS code.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "AcsDemographicsByState": {+ "description": "American Community Survey 5-year demographic, income, housing, employment, and education estimates for every US state.",+ "docs_url": "https://www.census.gov/data/developers/data-sets/acs-5year.html",+ "columns": _ACS_COLUMNS,+ },+ "AcsDemographicsByCounty": {+ "description": "American Community Survey 5-year demographic, income, housing, employment, and education estimates for every US county.",+ "docs_url": "https://www.census.gov/data/developers/data-sets/acs-5year.html",+ "columns": {+ **_ACS_COLUMNS,+ "county": "Three-digit county FIPS code, unique within its state.",+ },+ },+ "DecennialPopulationByState": {+ "description": "2020 Decennial Census (PL 94-171 redistricting data) population and housing unit counts for every US state.",+ "docs_url": "https://www.census.gov/data/developers/data-sets/decennial-census.html",+ "columns": _DECENNIAL_COLUMNS,+ },+ "DecennialPopulationByCounty": {+ "description": "2020 Decennial Census (PL 94-171 redistricting data) population and housing unit counts for every US county.",+ "docs_url": "https://www.census.gov/data/developers/data-sets/decennial-census.html",+ "columns": {+ **_DECENNIAL_COLUMNS,+ "county": "Three-digit county FIPS code, unique within its state.",+ },+ },+ "CountyBusinessPatternsByState": {+ "description": "County Business Patterns all-sector establishment, employment, and payroll totals for every US state.",+ "docs_url": "https://www.census.gov/data/developers/data-sets/cbp-zbp/cbp-api.html",+ "columns": {+ "NAME": "Human-readable name of the geography (state name).",+ "NAICS2017": "2017 NAICS industry code (00 = total for all sectors).",+ "NAICS2017_LABEL": "Human-readable label for the NAICS industry code.",+ "ESTAB": "Number of establishments.",+ "EMP": "Number of paid employees for the pay period including March 12.",+ "PAYANN": "Annual payroll in thousands of dollars.",+ "state": "Two-digit state FIPS code.",+ },+ },+ "PopulationEstimatesByState": {+ "description": "Population Estimates Program (vintage 2021) resident population and density for every US state.",+ "docs_url": "https://www.census.gov/data/developers/data-sets/popest-popproj/popest.html",+ "columns": {+ "NAME": "Human-readable name of the geography (state name).",+ "POP_2021": "Estimated resident population as of July 1, 2021.",+ "DENSITY_2021": "Estimated population density (persons per square mile) as of July 1, 2021.",+ "state": "Two-digit state FIPS code.",+ },+ },+ "CustomQuery": {+ "description": "Rows returned by the custom Census query configured on this source (dataset, variables, and geography chosen by the user).",+ "docs_url": "https://www.census.gov/data/developers/guidance/api-user-guide.html",+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/settings.pynew file mode 100644index 000000000000..8d6d8f3f879a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/settings.py@@ -0,0 +1,106 @@+import dataclasses++from products.warehouse_sources.backend.types import IncrementalField++CENSUS_API_BASE_URL = "https://api.census.gov/data"++# Documented API cap on the number of variables per `get=` clause.+MAX_VARIABLES_PER_QUERY = 50++# Schema name for the user-defined query built from the source's custom_* config fields.+CUSTOM_QUERY_ENDPOINT = "CustomQuery"++# Cheap probe used by validate_credentials: one variable, one row per state.+VALIDATION_DATASET = "2024/acs/acs5"+VALIDATION_GEOGRAPHY = "us:*"++[email protected](frozen=True)+class CensusEndpoint:+ dataset: str+ """Vintage/dataset path under api.census.gov/data, e.g. "2024/acs/acs5"."""+ variables: tuple[str, ...]+ """Census variable codes for the `get=` clause. The API also returns the geography id columns."""+ geography: str+ """`for=` geography clause, e.g. "state:*"."""+ primary_keys: tuple[str, ...]+ """Geography (plus any predicate) columns that uniquely identify a row."""+ predicates: tuple[tuple[str, str], ...] = ()+ """Extra filter params appended to the query, e.g. (("NAICS2017", "00"),)."""+++_ACS5_DATASET = "2024/acs/acs5"+_ACS5_VARIABLES = (+ "NAME",+ "B01001_001E", # total population+ "B01002_001E", # median age+ "B19013_001E", # median household income+ "B19301_001E", # per capita income+ "B25077_001E", # median home value+ "B23025_003E", # civilian labor force+ "B23025_005E", # unemployed+ "B15003_022E", # bachelor's degree holders (25+)+)++_DECENNIAL_DATASET = "2020/dec/pl"+_DECENNIAL_VARIABLES = (+ "NAME",+ "P1_001N", # total population+ "H1_001N", # total housing units+)++ENDPOINTS: dict[str, CensusEndpoint] = {+ "AcsDemographicsByState": CensusEndpoint(+ dataset=_ACS5_DATASET,+ variables=_ACS5_VARIABLES,+ geography="state:*",+ primary_keys=("state",),+ ),+ "AcsDemographicsByCounty": CensusEndpoint(+ dataset=_ACS5_DATASET,+ variables=_ACS5_VARIABLES,+ geography="county:*",+ primary_keys=("state", "county"),+ ),+ "DecennialPopulationByState": CensusEndpoint(+ dataset=_DECENNIAL_DATASET,+ variables=_DECENNIAL_VARIABLES,+ geography="state:*",+ primary_keys=("state",),+ ),+ "DecennialPopulationByCounty": CensusEndpoint(+ dataset=_DECENNIAL_DATASET,+ variables=_DECENNIAL_VARIABLES,+ geography="county:*",+ primary_keys=("state", "county"),+ ),+ "CountyBusinessPatternsByState": CensusEndpoint(+ dataset="2023/cbp",+ variables=("NAME", "NAICS2017", "NAICS2017_LABEL", "ESTAB", "EMP", "PAYANN"),+ geography="state:*",+ # NAICS2017 is a "default displayed" predicate; pin it to 00 (total for all+ # sectors) so the row grain stays one row per state across API changes.+ primary_keys=("state", "NAICS2017"),+ predicates=(("NAICS2017", "00"),),+ ),+ "PopulationEstimatesByState": CensusEndpoint(+ dataset="2021/pep/population",+ variables=("NAME", "POP_2021", "DENSITY_2021"),+ geography="state:*",+ primary_keys=("state",),+ ),+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "AcsDemographicsByState": "American Community Survey 5-year estimates (2020-2024) of population, income, housing, employment, and education for every US state.",+ "AcsDemographicsByCounty": "American Community Survey 5-year estimates (2020-2024) of population, income, housing, employment, and education for every US county.",+ "DecennialPopulationByState": "2020 Decennial Census (PL 94-171) population and housing unit counts for every US state.",+ "DecennialPopulationByCounty": "2020 Decennial Census (PL 94-171) population and housing unit counts for every US county.",+ "CountyBusinessPatternsByState": "County Business Patterns (2023) establishment, employment, and payroll totals for every US state.",+ "PopulationEstimatesByState": "Population Estimates Program (vintage 2021) population and density for every US state.",+ CUSTOM_QUERY_ENDPOINT: "Your own query against any Census dataset, built from the custom query fields on the source.",+}++# Census datasets are versioned by vintage and expose no server-side created/updated+# timestamp filters, so every table is full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/source.pyindex 89dbf88aa0ca..7f733dace4b6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/source.py@@ -1,32 +1,192 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.uscensus import (USCensusSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.settings import (+ CUSTOM_QUERY_ENDPOINT,+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.us_census import (+ AUTH_ERROR_MESSAGE,+ RESPONSE_TOO_LARGE_PREFIX,+ parse_custom_variables,+ us_census_source,+ validate_credentials as validate_us_census_credentials,+ validate_custom_query,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _has_custom_query(config: USCensusSourceConfig) -> bool:+ return bool(+ (config.custom_dataset or "").strip()+ and (config.custom_variables or "").strip()+ and (config.custom_geography or "").strip()+ )++@SourceRegistry.registerclass USCensusSource(SimpleSource[USCensusSourceConfig]):+ # Static endpoint catalog with no I/O in get_schemas — safe for public docs.+ lists_tables_without_credentials = True+ # The Census Data API is unversioned; datasets are versioned by vintage in the URL path.+ api_docs_url = "https://www.census.gov/data/developers/guidance/api-user-guide.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.USCENSUS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ AUTH_ERROR_MESSAGE: "Your US Census API key was rejected. Request a free key at https://api.census.gov/data/key_signup.html and update the source.",+ "unknown variable": "One of the requested variables does not exist in the selected dataset. Check the dataset's variable list at https://api.census.gov/data.html.",+ "unsupported geography": "The requested geography is not supported by the selected dataset. Check the dataset's geography list at https://api.census.gov/data.html.",+ "US Census custom query": "The custom query on this source is incomplete or invalid. Update the custom query fields on the source and retry.",+ RESPONSE_TOO_LARGE_PREFIX: "The query returned more data than a single sync can hold. Narrow the custom query with fewer variables or a smaller geography (e.g. an in= filter).",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: USCensusSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ endpoint_names = list(ENDPOINTS)+ if _has_custom_query(config):+ endpoint_names.append(CUSTOM_QUERY_ENDPOINT)+ return build_endpoint_schemas(endpoint_names, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)++ def validate_credentials(+ self, config: USCensusSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ custom_query_error = validate_custom_query(+ config.custom_dataset, config.custom_variables, config.custom_geography+ )+ if custom_query_error is not None:+ return False, custom_query_error++ return validate_us_census_credentials(config.api_key)++ def source_for_pipeline(self, config: USCensusSourceConfig, inputs: SourceInputs) -> SourceResponse:+ if inputs.schema_name == CUSTOM_QUERY_ENDPOINT:+ custom_query_error = validate_custom_query(+ config.custom_dataset, config.custom_variables, config.custom_geography+ )+ if custom_query_error is not None or not _has_custom_query(config):+ raise ValueError(custom_query_error or "US Census custom query is not configured on this source")+ assert config.custom_dataset is not None and config.custom_variables is not None+ assert config.custom_geography is not None+ return us_census_source(+ api_key=config.api_key,+ endpoint=CUSTOM_QUERY_ENDPOINT,+ dataset=config.custom_dataset.strip().strip("/"),+ variables=parse_custom_variables(config.custom_variables),+ geography=config.custom_geography.strip(),+ geography_filter=(config.custom_geography_filter or "").strip() or None,+ # The geography columns of an arbitrary query aren't known ahead of time,+ # and the table is full refresh only, so no primary keys are declared.+ primary_keys=None,+ )++ endpoint = ENDPOINTS[inputs.schema_name]+ return us_census_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ dataset=endpoint.dataset,+ variables=endpoint.variables,+ geography=endpoint.geography,+ predicates=endpoint.predicates,+ primary_keys=list(endpoint.primary_keys),+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.US_CENSUS,category=DataWarehouseSourceCategory.ANALYTICS,label="US Census",- iconPath="/static/services/us_census.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["census", "acs", "american community survey", "demographics", "government"],+ caption="Sync official US Census Bureau statistics. Get a free API key at [api.census.gov](https://api.census.gov/data/key_signup.html). To sync a dataset beyond the built-in tables, fill in the custom query fields using the dataset directory at [api.census.gov/data.html](https://api.census.gov/data.html).",+ docsUrl="https://posthog.com/docs/cdp/sources/us-census",+ iconPath="/static/services/us_census.svg",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="custom_dataset",+ label="Custom query: dataset path",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2024/acs/acs5",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="custom_variables",+ label="Custom query: variables (get)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="NAME,B01001_001E",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="custom_geography",+ label="Custom query: geography (for)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="state:*",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="custom_geography_filter",+ label="Custom query: parent geography (in)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="state:06",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/tests/test_us_census.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/tests/test_us_census.pynew file mode 100644index 000000000000..8bbfce6a11b6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/tests/test_us_census.py@@ -0,0 +1,201 @@+import json+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.settings import (+ ENDPOINTS,+ MAX_VARIABLES_PER_QUERY,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.us_census import (+ build_query_url,+ get_rows,+ parse_custom_variables,+ rows_from_payload,+ validate_credentials,+ validate_custom_query,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.us_census.us_census"+++def _mock_response(+ status_code: int = 200,+ json_data: Any = None,+ headers: Optional[dict[str, str]] = None,+ text: str = "",+) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.headers = headers or {}+ response.text = text+ body = json.dumps(json_data).encode() if json_data is not None else text.encode()+ response.iter_content.return_value = iter([body])+ return response+++def _patched_session(response: MagicMock):+ session = MagicMock()+ session.get.return_value = response+ return patch(f"{_MODULE}.make_tracked_session", return_value=session), session+++class TestUSCensus:+ def test_build_query_url_keeps_census_syntax_literal(self):+ url = build_query_url(+ "2024/acs/acs5",+ ("NAME", "B01001_001E"),+ "county:*",+ geography_filter="state:06",+ api_key="secret",+ )++ assert url == (+ "https://api.census.gov/data/2024/acs/acs5?get=NAME,B01001_001E&for=county:*&in=state:06&key=secret"+ )++ def test_build_query_url_with_predicates_and_no_optional_parts(self):+ url = build_query_url("2023/cbp", ("ESTAB",), "state:*", predicates=(("NAICS2017", "00"),))++ assert url == "https://api.census.gov/data/2023/cbp?get=ESTAB&for=state:*&NAICS2017=00"++ def test_rows_from_payload_zips_header_row(self):+ payload = [+ ["NAME", "B01001_001E", "state"],+ ["California", "39242785", "06"],+ ["Texas", "29527941", "48"],+ ]++ assert rows_from_payload(payload) == [+ {"NAME": "California", "B01001_001E": "39242785", "state": "06"},+ {"NAME": "Texas", "B01001_001E": "29527941", "state": "48"},+ ]++ @pytest.mark.parametrize("payload", [None, {}, [], "rows", [{"NAME": "x"}]])+ def test_rows_from_payload_rejects_unexpected_shapes(self, payload):+ with pytest.raises(ValueError, match="Unexpected response"):+ rows_from_payload(payload)++ def test_get_rows_yields_row_dicts(self):+ payload = [["NAME", "state"], ["California", "06"], ["Texas", "48"]]+ patcher, session = _patched_session(_mock_response(json_data=payload))++ with patcher:+ batches = list(get_rows("key", "2024/acs/acs5", ("NAME",), "state:*", None, ()))++ assert batches == [[{"NAME": "California", "state": "06"}, {"NAME": "Texas", "state": "48"}]]+ requested_url = session.get.call_args.args[0]+ assert "key=key" in requested_url++ @pytest.mark.parametrize(+ ("headers", "location"),+ [+ ({"X-DataWebAPI-KeyError": "1"}, ""),+ ({}, "https://api.census.gov/data/invalid_key.html"),+ ({}, "https://api.census.gov/data/missing_key.html"),+ ],+ )+ def test_get_rows_raises_auth_error_on_key_redirect(self, headers, location):+ response = _mock_response(status_code=302, headers={**headers, "Location": location})++ patcher, _ = _patched_session(response)+ with patcher, pytest.raises(ValueError, match="US Census API key is missing or invalid"):+ list(get_rows("bad-key", "2024/acs/acs5", ("NAME",), "state:*", None, ()))++ def test_get_rows_surfaces_api_error_body(self):+ response = _mock_response(status_code=400, text="error: unknown variable 'B99999_999E'")++ patcher, _ = _patched_session(response)+ with patcher, pytest.raises(ValueError, match="unknown variable"):+ list(get_rows("key", "2024/acs/acs5", ("B99999_999E",), "state:*", None, ()))++ def test_get_rows_rejects_non_json_success_body(self):+ patcher, _ = _patched_session(_mock_response(text="<html>...</html>"))++ with patcher, pytest.raises(ValueError, match="not valid JSON"):+ list(get_rows("key", "2024/acs/acs5", ("NAME",), "state:*", None, ()))++ def test_get_rows_rejects_oversized_response(self):+ payload = [["NAME", "state"], ["California", "06"]]+ patcher, _ = _patched_session(_mock_response(json_data=payload))++ with patcher, patch(f"{_MODULE}._MAX_RESPONSE_BYTES", 8), pytest.raises(ValueError, match="too large"):+ list(get_rows("key", "2024/acs/acs5", ("NAME",), "state:*", None, ()))++ @pytest.mark.parametrize(+ ("status_code", "headers", "expected_valid", "expected_error_fragment"),+ [+ (200, {}, True, None),+ (302, {"X-DataWebAPI-KeyError": "1"}, False, "rejected"),+ (500, {}, False, "unexpected status"),+ ],+ )+ def test_validate_credentials_status_mapping(self, status_code, headers, expected_valid, expected_error_fragment):+ payload = [["NAME"], ["United States"]] if status_code == 200 else None+ patcher, _ = _patched_session(_mock_response(status_code=status_code, json_data=payload, headers=headers))++ with patcher:+ valid, error = validate_credentials("some-key")++ assert valid is expected_valid+ if expected_error_fragment is None:+ assert error is None+ else:+ assert error is not None and expected_error_fragment in error++ def test_validate_credentials_requires_key(self):+ valid, error = validate_credentials(" ")++ assert valid is False+ assert error is not None and "required" in error++ def test_validate_credentials_handles_network_failure(self):+ session = MagicMock()+ session.get.side_effect = ConnectionError("boom")++ with patch(f"{_MODULE}.make_tracked_session", return_value=session):+ valid, error = validate_credentials("some-key")++ assert valid is False+ assert error is not None and "Could not reach" in error++ def test_parse_custom_variables_strips_whitespace_and_empties(self):+ assert parse_custom_variables(" NAME , B01001_001E ,, ") == ("NAME", "B01001_001E")++ @pytest.mark.parametrize(+ ("dataset", "variables", "geography", "expected_fragment"),+ [+ (None, None, None, None),+ ("", " ", "", None),+ ("2024/acs/acs5", "NAME", "state:*", None),+ ("2024/acs/acs5", None, None, "incomplete"),+ (None, "NAME", "state:*", "incomplete"),+ ("2024/acs/acs5?x=1", "NAME", "state:*", "dataset path is invalid"),+ ("2024/acs/acs5", " , ", "state:*", "variables are invalid"),+ (+ "2024/acs/acs5",+ ",".join(f"VAR{i}" for i in range(MAX_VARIABLES_PER_QUERY + 1)),+ "state:*",+ "too many variables",+ ),+ ],+ )+ def test_validate_custom_query(self, dataset, variables, geography, expected_fragment):+ error = validate_custom_query(dataset, variables, geography)++ if expected_fragment is None:+ assert error is None+ else:+ assert error is not None and expected_fragment in error++ @pytest.mark.parametrize("endpoint_name", list(ENDPOINTS))+ def test_endpoint_catalog_is_well_formed(self, endpoint_name):+ endpoint = ENDPOINTS[endpoint_name]++ assert 0 < len(endpoint.variables) <= MAX_VARIABLES_PER_QUERY+ assert len(set(endpoint.variables)) == len(endpoint.variables)+ assert ":" in endpoint.geography+ assert len(endpoint.primary_keys) > 0+ assert validate_custom_query(endpoint.dataset, ",".join(endpoint.variables), endpoint.geography) is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/tests/test_us_census_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/tests/test_us_census_source.pynew file mode 100644index 000000000000..918ee9c7d640--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/tests/test_us_census_source.py@@ -0,0 +1,146 @@+import pytest+from unittest.mock import patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.uscensus import (+ USCensusSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.settings import (+ CUSTOM_QUERY_ENDPOINT,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.source import USCensusSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(**overrides) -> USCensusSourceConfig:+ return USCensusSourceConfig(api_key="test-key", **overrides)+++def _custom_config() -> USCensusSourceConfig:+ return _config(+ custom_dataset="2024/acs/acs5",+ custom_variables="NAME,B01001_001E",+ custom_geography="state:*",+ )+++class _FakeInputs:+ def __init__(self, schema_name: str) -> None:+ self.schema_name = schema_name+++class TestUSCensusSource:+ def setup_method(self):+ self.source = USCensusSource()++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.USCENSUS++ def test_source_config_is_released_alpha(self):+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/us-census"++ def test_source_config_fields(self):+ fields = {field.name: field for field in self.source.get_source_config.fields}++ api_key_field = fields["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True+ for name in ("custom_dataset", "custom_variables", "custom_geography", "custom_geography_filter"):+ custom_field = fields[name]+ assert isinstance(custom_field, SourceFieldInputConfig)+ assert custom_field.required is False++ def test_get_schemas_static_catalog(self):+ schemas = self.source.get_schemas(_config(), team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ assert all(schema.supports_incremental is False for schema in schemas)+ assert all(schema.supports_append is False for schema in schemas)+ assert all(schema.description for schema in schemas)++ def test_get_schemas_includes_custom_query_when_configured(self):+ schemas = self.source.get_schemas(_custom_config(), team_id=1)++ assert [schema.name for schema in schemas] == [*ENDPOINTS, CUSTOM_QUERY_ENDPOINT]++ def test_get_schemas_names_filter(self):+ schemas = self.source.get_schemas(_config(), team_id=1, names=["AcsDemographicsByState"])++ assert [schema.name for schema in schemas] == ["AcsDemographicsByState"]++ @pytest.mark.parametrize(+ "overrides",+ [+ {"custom_dataset": "2024/acs/acs5"},+ {"custom_dataset": "2024/acs/acs5", "custom_variables": "NAME"},+ {"custom_variables": "NAME", "custom_geography": "state:*"},+ ],+ )+ def test_validate_credentials_rejects_partial_custom_query(self, overrides):+ valid, error = self.source.validate_credentials(_config(**overrides), team_id=1)++ assert valid is False+ assert error is not None and "incomplete" in error++ def test_validate_credentials_delegates_to_transport(self):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.us_census.source.validate_us_census_credentials",+ return_value=(True, None),+ ) as mock_validate:+ valid, error = self.source.validate_credentials(_config(), team_id=1)++ assert (valid, error) == (True, None)+ mock_validate.assert_called_once_with("test-key")++ @pytest.mark.parametrize("endpoint_name", list(ENDPOINTS))+ def test_source_for_pipeline_builds_catalog_endpoint(self, endpoint_name):+ response = self.source.source_for_pipeline(_config(), _FakeInputs(endpoint_name)) # type: ignore[arg-type]++ assert response.name == endpoint_name+ assert response.primary_keys == list(ENDPOINTS[endpoint_name].primary_keys)++ def test_source_for_pipeline_custom_query_plumbing(self):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.us_census.source.us_census_source"+ ) as mock_source:+ self.source.source_for_pipeline(_custom_config(), _FakeInputs(CUSTOM_QUERY_ENDPOINT)) # type: ignore[arg-type]++ kwargs = mock_source.call_args.kwargs+ assert kwargs["dataset"] == "2024/acs/acs5"+ assert kwargs["variables"] == ("NAME", "B01001_001E")+ assert kwargs["geography"] == "state:*"+ assert kwargs["geography_filter"] is None+ assert kwargs["primary_keys"] is None++ def test_source_for_pipeline_custom_query_unconfigured_raises(self):+ with pytest.raises(ValueError, match="US Census custom query"):+ self.source.source_for_pipeline(_config(), _FakeInputs(CUSTOM_QUERY_ENDPOINT)) # type: ignore[arg-type]++ @pytest.mark.parametrize(+ "error_message",+ [+ "US Census API key is missing or invalid. Request a free key at https://api.census.gov/data/key_signup.html",+ "US Census API rejected the request (400): error: unknown variable 'B99999_999E'",+ "US Census API rejected the request (400): error: unsupported geography hierarchy",+ "US Census custom query is incomplete: set the dataset path, variables, and geography together",+ "US Census API response is too large (over 256 MiB). Narrow the query with fewer variables or a smaller geography (e.g. an in= filter).",+ ],+ )+ def test_known_permanent_failures_are_non_retryable(self, error_message):+ non_retryable = self.source.get_non_retryable_errors()++ assert any(pattern in error_message for pattern in non_retryable)++ def test_canonical_descriptions_cover_catalog_endpoints(self):+ descriptions = self.source.get_canonical_descriptions()++ for endpoint_name in ENDPOINTS:+ assert endpoint_name in descriptions+ assert descriptions[endpoint_name].get("description")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/us_census.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/us_census.pynew file mode 100644index 000000000000..7d08e7e3afd5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_census/us_census.py@@ -0,0 +1,184 @@+import re+import json+from collections.abc import Iterator, Sequence+from typing import Any, Optional+from urllib.parse import urlencode++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.us_census.settings import (+ CENSUS_API_BASE_URL,+ MAX_VARIABLES_PER_QUERY,+ VALIDATION_DATASET,+ VALIDATION_GEOGRAPHY,+)++_REQUEST_TIMEOUT = 120++# Rows per yielded chunk. The full response is already in memory (the API has no+# pagination), so this only bounds the size of each batch handed to the pipeline.+_ROWS_PER_CHUNK = 5000++# The API signals a missing/invalid key with a 302 to an HTML error page and this header.+_KEY_ERROR_HEADER = "X-DataWebAPI-KeyError"++AUTH_ERROR_MESSAGE = "US Census API key is missing or invalid"+REQUEST_ERROR_PREFIX = "US Census API rejected the request"+RESPONSE_SHAPE_ERROR_PREFIX = "Unexpected response from the US Census API"+RESPONSE_TOO_LARGE_PREFIX = "US Census API response is too large"++# Cap on the decoded response body. The API has no pagination, so a high-cardinality+# custom query (e.g. every census block nationwide) would otherwise buffer an unbounded+# body plus parsed copies in memory.+_MAX_RESPONSE_BYTES = 256 * 1024 * 1024+_STREAM_CHUNK_BYTES = 1024 * 1024++_DATASET_PATH_REGEX = re.compile(r"^[A-Za-z0-9][A-Za-z0-9/_.-]*$")+++def build_query_url(+ dataset: str,+ variables: Sequence[str],+ geography: str,+ geography_filter: Optional[str] = None,+ predicates: Sequence[tuple[str, str]] = (),+ api_key: str = "",+) -> str:+ params: list[tuple[str, str]] = [("get", ",".join(variables)), ("for", geography)]+ if geography_filter:+ params.append(("in", geography_filter))+ params.extend(predicates)+ if api_key:+ params.append(("key", api_key))+ # Keep `:`, `*`, and `,` literal — the documented Census query syntax uses them raw+ # (e.g. for=state:*), and percent-encoding them is unverified against this API.+ return f"{CENSUS_API_BASE_URL}/{dataset.strip('/')}?{urlencode(params, safe=':*,')}"+++def _is_key_error(response: Response) -> bool:+ return response.status_code in (301, 302, 303, 307, 308) and (+ response.headers.get(_KEY_ERROR_HEADER) is not None or "key" in response.headers.get("Location", "").lower()+ )+++def _raise_for_error(response: Response) -> None:+ if _is_key_error(response):+ raise ValueError(f"{AUTH_ERROR_MESSAGE}. Request a free key at https://api.census.gov/data/key_signup.html")+ if not response.ok:+ # 4xx bodies carry the reason as plain text (e.g. "error: unknown variable 'X'").+ raise ValueError(f"{REQUEST_ERROR_PREFIX} ({response.status_code}): {response.text[:500]}")+++def rows_from_payload(payload: Any) -> list[dict[str, Any]]:+ """Zip the Census 2D array-of-arrays payload (first row = column headers) into row dicts."""+ if not isinstance(payload, list) or not payload or not isinstance(payload[0], list):+ raise ValueError(f"{RESPONSE_SHAPE_ERROR_PREFIX}: expected a JSON array of arrays")+ header = [str(column) for column in payload[0]]+ return [dict(zip(header, row)) for row in payload[1:]]+++def parse_custom_variables(raw: str) -> tuple[str, ...]:+ return tuple(variable.strip() for variable in raw.split(",") if variable.strip())+++def validate_custom_query(+ dataset: Optional[str],+ variables: Optional[str],+ geography: Optional[str],+) -> str | None:+ """Validate the custom query config fields; returns a user-facing error message or None."""+ values = (dataset or "", variables or "", geography or "")+ if not any(value.strip() for value in values):+ return None+ if not all(value.strip() for value in values):+ return "US Census custom query is incomplete: set the dataset path, variables, and geography together"+ assert dataset is not None and variables is not None and geography is not None+ if not _DATASET_PATH_REGEX.match(dataset.strip().strip("/")):+ return "US Census custom query dataset path is invalid: use a vintage/dataset path like 2024/acs/acs5"+ parsed_variables = parse_custom_variables(variables)+ if not parsed_variables:+ return "US Census custom query variables are invalid: provide a comma-separated list like NAME,B01001_001E"+ if len(parsed_variables) > MAX_VARIABLES_PER_QUERY:+ return f"US Census custom query requests too many variables: the API allows at most {MAX_VARIABLES_PER_QUERY} per query"+ return None+++def get_rows(+ api_key: str,+ dataset: str,+ variables: Sequence[str],+ geography: str,+ geography_filter: Optional[str],+ predicates: Sequence[tuple[str, str]],+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ url = build_query_url(dataset, variables, geography, geography_filter, predicates, api_key)+ # Stream so an oversized body is rejected at the byte cap instead of buffered whole;+ # the request timeout applies per read between chunks, bounding the transfer.+ response = session.get(url, timeout=_REQUEST_TIMEOUT, stream=True)+ _raise_for_error(response)++ body = bytearray()+ for chunk in response.iter_content(chunk_size=_STREAM_CHUNK_BYTES):+ body.extend(chunk)+ if len(body) > _MAX_RESPONSE_BYTES:+ response.close()+ raise ValueError(+ f"{RESPONSE_TOO_LARGE_PREFIX} (over {_MAX_RESPONSE_BYTES // (1024 * 1024)} MiB). "+ "Narrow the query with fewer variables or a smaller geography (e.g. an in= filter)."+ )++ try:+ payload = json.loads(bytes(body))+ except ValueError as e:+ raise ValueError(f"{RESPONSE_SHAPE_ERROR_PREFIX}: body is not valid JSON") from e++ rows = rows_from_payload(payload)+ for start in range(0, len(rows), _ROWS_PER_CHUNK):+ yield rows[start : start + _ROWS_PER_CHUNK]+++def us_census_source(+ api_key: str,+ endpoint: str,+ dataset: str,+ variables: Sequence[str],+ geography: str,+ geography_filter: Optional[str] = None,+ predicates: Sequence[tuple[str, str]] = (),+ primary_keys: Optional[list[str]] = None,+) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ dataset=dataset,+ variables=variables,+ geography=geography,+ geography_filter=geography_filter,+ predicates=predicates,+ ),+ primary_keys=primary_keys,+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ if not api_key or not api_key.strip():+ return False, "US Census API key is required. Request a free key at https://api.census.gov/data/key_signup.html"++ url = build_query_url(VALIDATION_DATASET, ("NAME",), VALIDATION_GEOGRAPHY, api_key=api_key)+ try:+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(url, timeout=30)+ except Exception:+ return False, "Could not reach the US Census API. Please try again later."++ if response.status_code == 200:+ return True, None+ if _is_key_error(response):+ return (+ False,+ "US Census API key was rejected. Request a free key at https://api.census.gov/data/key_signup.html",+ )+ return False, f"US Census API returned an unexpected status ({response.status_code}). Please try again later."