* it works...
* clean up server side
* move logic from query to helpers/api
* typing fixes
* add tests to helpers
* test for metadata queries
* api tests
* util tests
* improve some types and move logic to utils
* Get PlayerMeta working
* tests for sessionRecordingPlayerLogic
* fix some more tests
* analytics fix
* name flip
* player util tests
* Add comments + remove logs
* Clean up some comments
* make is_active a bit cleaner
* remove some log statements
* add comment to metadata function
* some cleanup
* typescript fix
* timestamp plays follows scrubbing
* fix bug with hitting 60 seconds
* fix end position bug
* fix bugs with skip ahead
* fix some bugs
* fix white screen on buffer end
* fix buffer scrubbing bugs
* fix skip bug
* fix circular import
* rename start_window_id to last_active_window_id
* fix tests
* bug fix for no window_id case
* fix bug when scrubbing to the end of the player
* rename setBuffer + setScrub to startBuffer + startScrub
* fix(retention): fix breakdown people urls
This change returns people_url for each breakdown cohort in the
response. We also merge the initial and returning queries together,
as this makes it easier to align the people query also.
Note that I'm talking about person_id as opposed to actor_type etc.
but perhaps that can be a followup.
* clean up clickhouse params
* tidy up a little
* remove import
* remove non-breakdown specific code
* make cohort by initial event date a special breakdown case
* keep date for backwards compat
* Remove unused sql
* make test stable
* wip
* Get most of the tests working
* test(retention): remove graph retention test
We no longer need this, we have all the information we need from the
table response for retention, and can construct this on the frontend.
* revert any changes to posthog/queries/retention.py
* revert any changes to ee/clickhouse/models/person.py
* Revert posthog/queries/retention.py to merge-base
* Ensure actor id is a str
* Add type for actor serialiser for type narrowing
* run black
* sort imports
* Remove retention_actors.py
* fix typings
* format
* reverse str type
* sort imports
* rename
* split out functions
* remove deuplicate logic
* working
* fix type
* don't stringify
* fix test
* ordering doesn't matter
* trigger ci
Co-authored-by: eric <eeoneric@gmail.com>
* Make person hooks only happen in tests
* Remove a data script
* Update split_person code to handle hookless life
* Delete clickhouse data async in the background
* Make settings dynamic for MATERIALIZED_COLUMNS_ENABLED
* migrate MATERIALIZED_COLUMNS_ENABLED to this and test
* allow tests that use materialized columns to hit django model for settings
* nicer installed apps config
* update snapshot from test
* make test_property more deterministic
Co-authored-by: James Greenhill <fuzionech@gmail.com>
Co-authored-by: yakkomajuri <yakko.majuri@gmail.com>
* Resolve another insights N+1 issue
Using `prefetch_related` to avoid loading the same dashboard/user
multiple times if referred to by different insights. More queries _can_
be better! :)
* Improve the test
* Get test stable, add created_by user
* error if unsupported db version
* upgrade mypy
* fix various types for mypy
* you can have it in any color you want, as long as it's black
* fix mypy
* Update `kafka-python`
* Format with Black
* Fix mypy after merge
Co-authored-by: Michael Matloka <dev@twixes.com>
* Order by created_at over id in groups list, similar to persons
* Change table column name to be consistent with persons
* Default to `.name` property if one is passed for groups
This improves a usability issue with groups temporarily
* convert to actor form
* change var name
* remove unused imports
* typing issue
* use subquery
* bad import
* groups for general retention query
* actor in period
* update imports
* update test
* remove comment
* Add group analytics to list of paid features
* Add team-level property for if any group types exist
* WIP: Groups introduction page
* Finish initial empty state page
* Hide upsell if not CH or flag not live
* Extract upsell-related logic into a separate logic to avoid loading data unless needed
* Extract upgradeLink
* Extract announcement logic
* Overcomplicate announcements
* Show initial groups announcement.
* Vary banner content according to groups access status
* Clean up access logic
* Misc announcements improvement
* Add a feature flag for groups announcement given docs are not yet ready
* Keep color for visited button links
* Get groupsList logic tests working
teamLogic <-> userLogic test connection needed to be severed alongside
this
* Migration to add version to person_distinct_id
* Update plugin-server type
* Use queueMessages instead of for loops
* Update distinct id versions in postgres
* Add commented out new query
* Add person_distinct_id2 table setup/migration
This will be used for more efficient person_distinct_id queries
* Avoid sharding person_distinct_id2 on cloud
* Write to new distinct ids topic
* Attempt to use version in tests
* Tests attempt 2
* Fixup version - dont send with all messages
* Flush kafka more frequently
* Actually fix tests
* Add another await
* Add partition to person_distinct_id2 table
* Add a comment to keep topics in sync
* Clean up code relating to table engines
* Add snapshots for table creation queries
* Remove optional import
* Add snapshot tests for CLICKHOUSE_REPLICATION schemas
Note that these are out of sync with cloud in most cases
* Add another warning comment
* Improve naming
* Create a new way to get distinct id queries thats gated by team_id
* Update most cases to use the new query
* Convert EVENT_JOIN_PERSON_SQL to new query
* Mostly convert GET_DISTINCT_IDS_BY_PERSON_ID_FILTER
* Mostly convert GET_DISTINCT_IDS_BY_PROPERTY_SQL
* Convert GET_PERSON_IDS_BY_FILTER
* Flag benchmarks
* Resolve circular imports
* Update a snapshot test
* Add a test for the new query logic
* Add logging to all postgresql queries with query context
Uses the exact same pattern as we do currently for clickhouse, just
hooking in there differently
* Support psycopg2.sql.SQL
* Better docs
* update a test
* test(retention): add http api tests for retention breakdowns
This just adds tests for person and event property breakdowns
* Add helper function for substituting clickhouse sql params
* feat(retention): add support for multiple breakdown props
This just reuses the work done for funnel multiple breakdown values. I
haven't tested this with anything other than person or event properties.
Rather than try to get it working for all the other property types.
The change adds a new `breakdowns` parameter to the retention endpoint,
that is the same as for funnels, e.g. it looks like:
```
{
...
"breakdowns": [{"type": "person", "property": "os"}, ...]
...
}
```
The return structure is the same as the non-breakdown version, except we
also include a `breakdown_values` property that is e.g. `["Chrome",
"95"]`, and the `label` attribute for this case would be "Chrome::95".
* fix typing
* update query snapshots
* remove unused imports
* use `self.assertEqual` instead of `assert`
* Remove explicit should_join_persons
* Revert limit by changes, use breakdown_type
* update snapshots
* fix typing
* use json_encode_request_params in retention test requests
* update json_encode_request_params to encode_get_request_params to better reflect purpose
* perf(retention): add benchmark query for retention with breakdown
* no materialize
* Use GroupTypeIndex type in BE
* Consistent ordering for group types
* Better BE type for group type index
* Handle non-url safe keys in groups
Previously this would crash due to never decoding the url and not
handling it in the backend
* Allow fetching related groups from the API
* Solve minor type errors
* Add a tooltip
* data-attr for tracking links
* Add related groups onto person page
* Fix an import
* Kill useEffect
This was pretty much as copy paste job from the stickiness cases. I'm
going to be merging in some changes to retention so I want to get this
in first such that we can see if it affects the perf of these queries at
all. I don't think it touches them, as seen by the snapshot queries
generated by the retention tests not changing in
https://github.com/PostHog/posthog/pull/7431 but better safe than sorry.
Addresses [this comment](https://github.com/PostHog/posthog/pull/7431#pullrequestreview-820773405)
Fixes
> ee/clickhouse/queries/paths/paths_actors.py:30: error: Incompatible types in assignment (expression has type "PathFilter", base class "ActorBaseQuery" defined the type as "Filter")
Caused by parallel merges & weird typing-related issues.
* query for events with matching session_id if possible
* move test to clickhouse
* move event list to list instead of set for flaky test snapshot
* join events only when needed
* trigger benchmarking
* typo
* refactor(stickiness): refactor one stickiness test to use api
This change demonstrates how to migrate a `Query` object level test to
an api based test. It purely focuses on the method of action invocation
and not on any of the e.g. setup or assertions. The StickinessQuery
object is only used by the REST API (and benchmarking), where as the
REST stickiness API is used by external users including our own frontend
developers, so makes sense to test at this level.
* Migrate stickiness query tests to api
This doesn't touch the stickiness people API however
* Migrate clickhouse specific stickiness tests
* Migrate stickiness people query tests to http api level
NOTE! This isn't just a straight migration, but also makes one important
change to application code that would otherwise result in a test
failure. Specifically, when trying to find an action based on the
`entity_id` query param, we need to consider that the entity_id is a
string. This is fine for when trying to find events, as we are comparing
event ids which are strings, but for actions the id is an int, so we
need to ensure we cast the action id to a string before comparison.
* Move stickiness query tests to api tests location
* make stickiness tests stable across postgres/clickhouse
* Add comment regarding casting action ids to strings
* Update wording
* Update view to use postgres tables
We keep these in sync now
* Add retrieve endpoint
* Link to a (blank) groups page
* Show events table and properties under group
* Update pagination for groups
* update testing utils
* Update tests
* Patch tests relying on returned models
* Remove duplicated line
* Extract common subquery into a variable
* BE: handle group properties in more cases
* Add tests for lifecycle and sessions query changes
* Better docs
* Stable date range
* wip
* normalise to breakdown and breakdowns on the way out of the API
* read from breakdowns or breakdown property of filters
* wip
* wip
* delete a console.log
* remove console.log and speculative multi breakdown changes
* remove empty test
* remove console log
* more tidying
* more tidying
* more tidying
* simplify funnel logic slightly
* a test for the data transformations with no breakdown
* can test data transformation with a single property breakdown
* keep expanding the test to see why multi prop doesn't display
* don't throw key error if there is no breakdown property to pop from the multi property API response
* funnel step table can detect breakdown without relying on filter
* try to highlight the differences in the paths through TaxonomicBreakdownFilter
* better behaviour when adding and removing multi property breakdowns
* displays multi property breakdown in old style steps funnel views
* it is safe to always show breakdown in new vertical layout
* resolve multi property breakdown typehinting
* updates comment
* updates comment
* don't print breakdown value twice
* tooltip for long values and prettier pill
* convert tests to journeys_for
* fix multi breakdown helper
* better behaviour when navigating between trends and funnels
* Refactor the multi property breakdown helper to calm the mypy type checker down
* safer access to dict in multi property helper
* makes clean filters feature flags aware and keeps breakdown values when switching between trends and funnels
* test fix
* remove overly verbose data tests
* add some more specific tests to multi prop breakdown
* obey mypy
* remove the breakdown type from the backend which was causing serialization issues
* working for unique_groups math
* fix types
* add null check
* update snapshots
* update payload
* update snapshots
* use constructor
* adjust queries
* introduce base class
* consolidate querying
* shared serializer and typed
* sort imports
* snapshots
* typing
* change name
* Add group model
```sql
BEGIN;
--
-- Create model Group
--
CREATE TABLE "posthog_group" ("id" serial NOT NULL PRIMARY KEY, "group_key" varchar(400) NOT NULL, "group_type_index" integer NOT NULL, "group_properties" jsonb NOT NULL, "created_at" timestamp with time zone NOT NULL, "properties_last_updated_at" jsonb NOT NULL, "properties_last_operation" jsonb NOT NULL, "version" bigint NOT NULL, "team_id" integer NOT NULL);
--
-- Create constraint unique team_id/group_key/group_type_index combo on model group
--
ALTER TABLE "posthog_group" ADD CONSTRAINT "unique team_id/group_key/group_type_index combo" UNIQUE ("team_id", "group_key", "group_type_index");
ALTER TABLE "posthog_group" ADD CONSTRAINT "posthog_group_team_id_b3aed896_fk_posthog_team_id" FOREIGN KEY ("team_id") REFERENCES "posthog_team" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "posthog_group_team_id_b3aed896" ON "posthog_group" ("team_id");
COMMIT;
```
* Remove a dead import
* Improve typing for groups
* Make groups updating more generic, avoid mutation
This simplifies using the same logic for groups
Note there's a behavioral change: We don't produce a new kafka message
if nothing has been updated anymore.
* Rename a function
* WIP: Handle group property updates
... by storing them in postgres
Uses identical pattern to person property updates, except we handle
first-seen case within updates as well.
* Get rid of boolean option
* WIP continued
* fetchGroup() and upsertGroup()
* Test more edge cases
* Add tests for upsertGroup() in properties-updater
* Rename to PropertyUpdateOperation
* Followup
* Solve typing issues
* changed implementation to use pg
* unusd
* update type
* update snapshots
* rename and remove inlining
* restore bad merge code
* adjust types
* add flag
* remove var
* misnamed
* change to uuid
* make sure to use string when passing result
* remove from columnoptimizer logic and have group join logic implemented by event query classes per insight
* add flag to funnel event query
* remove unnecessary logic
* typing
* working actors func
* fix typos
* remove unused func
* use serialized result
* wrong var
* use actors
* remove dead imports
* remove verbosity
* update snapshots
* typos
* remove signals
* remove plugin excess
* update typing
* clean up
* use actor func for all funnel persons
* types
* make sure limits are set
* remove functions
* fix limits
* funnel trends
* types
* indexing
* moved basic funnel tests
* unordered test
* remove duplicate test
* check ids
* more test adjustments
* sort
* change class names
* sort
* reformat
* change string to int
* remove duplicate
* update comment
* use actor result to paginate not serialized
* adjust tests after merging
* simplify typing
* don't import removed func
Co-authored-by: Karl-Aksel Puulmann <oxymaccy@gmail.com>
* don't add leading slash to absolute url with no protocol
* don't add a base uri in only one funnel instantiation - will probably break tests
* remove console logs
* every API verb normalises URLs
* Tiny rename
* Minor refactor
* Test on FeatureFlagMatcher
* Add a field to feature_flag indicating if aggregating by groups
* Use f-strings
* Handle property filter building for group property
* Rename is_person_query
* Add message
* Tests for property_to_Q changes
* Add tests for groups w/ rollout
* Add comment for my_flags
* Hook up decide with groups
* New test helper for snapshotting pg queries
* Add snapshot tests for feature flags
* More is_simple_flag tests
* Add decide endpoint tests
* move conftest for ee tests to work
* Fix typo
* conftest troubles
* query for events with matching session_id if possible
* move test to clickhouse
* move event list to list instead of set for flaky test snapshot
* comment to clarify test
* original behaviour was to set breakdown_values regardless of if it was truthy
* add a test for the bug
* ensmallen the test case
* lift tested interface up a level
* implement multi property breakdown as an array from the spike
* correct type hint on method
* really resolve the conflict
* don't break groups
* refactor test assertions for breakdown cases
* adds a test to prove that funnels can receive a string and not an array
* protect saved dashboards from multi property changeover
* WIP
* multi breakdown working with funnel step breakdown
* prove funnel step person breakdown works with multi property breakdown
* don't need to protect cached dashboards from multi property breakdowns when they can't be set from the UI
* capitalise keywords in SQL
* convert a single test to journey helper
* wip
* account for funnel step breakdown sometimes being an array sent as a string
* safer handling of funnel step breakdown
* convert a test
* revert commits that made things worse
* simpler handling of funnel step breakdown
* no need to change funnel step breakdown type hint
* update imports
* guard against integer properties
* compare funnel step breakdown differently now there are arrays involved
* look for strict intersection for funnel step breakdown
* update test snapshots
* need to set breakdown_values earlier in processing
* remove tests that cover speculative functionality
* update snapshot
* move setup of breakdown values back out of update_filters
* update snapshots
* remove a sql parameter that was never assigned to
* Update ee/clickhouse/models/test/test_property.py
Co-authored-by: Harry Waye <harry@posthog.com>
* Update ee/clickhouse/queries/funnels/base.py
Co-authored-by: Harry Waye <harry@posthog.com>
* address review comment to simplify reading json expressions for breakdown
* clarify why some uses of get_property_string_expr escape params before passing
* add keyword arguments for calls to getting property string expressions in funnels
* switch to keyword arguments in test helper method
* fix parameterised test
* add multi property materialized column tests
* introduce the shim to allow new API for breakdown properties
* can't remove the naive funnel step breakdown list detection
* move funnel step breakdown list handling
* better handling of numeric funnel step breakdown values
* update snapshots
Co-authored-by: Harry Waye <harry@posthog.com>
* set debug, test, and primary_db env variables based on context
* remove unnecessary print
* also use pytest.ini for some tests run straight from pytest at the CLI
* Addtest for people_urls in retention trend response
* Add people_urls to retention trend response
* Run black formater
* sort imports
* Add default value for base_uri
* Let type be missing in EventPattern in tests
TypedDict is so rubbish in not allowing missing attributes 🤷
* fix typing
* refactor creation helper functions
* revert docker compose change
* working for unique_groups math
* fix types
* add null check
* update snapshots
* update payload
* update snapshots
* use constructor
* adjust queries
* introduce base class
* consolidate querying
* shared serializer and typed
* sort imports
* snapshots
* typing
* change name
* Add group model
```sql
BEGIN;
--
-- Create model Group
--
CREATE TABLE "posthog_group" ("id" serial NOT NULL PRIMARY KEY, "group_key" varchar(400) NOT NULL, "group_type_index" integer NOT NULL, "group_properties" jsonb NOT NULL, "created_at" timestamp with time zone NOT NULL, "properties_last_updated_at" jsonb NOT NULL, "properties_last_operation" jsonb NOT NULL, "version" bigint NOT NULL, "team_id" integer NOT NULL);
--
-- Create constraint unique team_id/group_key/group_type_index combo on model group
--
ALTER TABLE "posthog_group" ADD CONSTRAINT "unique team_id/group_key/group_type_index combo" UNIQUE ("team_id", "group_key", "group_type_index");
ALTER TABLE "posthog_group" ADD CONSTRAINT "posthog_group_team_id_b3aed896_fk_posthog_team_id" FOREIGN KEY ("team_id") REFERENCES "posthog_team" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "posthog_group_team_id_b3aed896" ON "posthog_group" ("team_id");
COMMIT;
```
* Remove a dead import
* Improve typing for groups
* Make groups updating more generic, avoid mutation
This simplifies using the same logic for groups
Note there's a behavioral change: We don't produce a new kafka message
if nothing has been updated anymore.
* Rename a function
* WIP: Handle group property updates
... by storing them in postgres
Uses identical pattern to person property updates, except we handle
first-seen case within updates as well.
* Get rid of boolean option
* WIP continued
* fetchGroup() and upsertGroup()
* Test more edge cases
* Add tests for upsertGroup() in properties-updater
* Rename to PropertyUpdateOperation
* Followup
* Solve typing issues
* changed implementation to use pg
* unusd
* update type
* update snapshots
* rename and remove inlining
* restore bad merge code
* adjust types
* add flag
* remove var
* misnamed
* change to uuid
* make sure to use string when passing result
* remove from columnoptimizer logic and have group join logic implemented by event query classes per insight
* remove unnecessary logic
* typing
* remove dead imports
* remove verbosity
* update snapshots
* typos
* remove signals
* remove plugin excess
Co-authored-by: Karl-Aksel Puulmann <oxymaccy@gmail.com>
I built this image a while ago, it's built with `yarn
arm64:build:clickhouse`, then I did a multipart build to copy only one
binary over and symlinking the various incantations (eg. server, client
etc) to keep the size down.
* WIP persons table schema migration
* add version to create_person
* test increased timeout
* Update ee/clickhouse/migrations/0019_person_table_version_column.py
* remove flaky kafka test
* format
* test a new approach - make this a non-large migration?
* Update ee/clickhouse/migrations/0021_person_table_version_column.py
* update
* Refactor stickiness to have its own event_query
This will speed up queries significantly and allow for filtering by
group properties
* Use same event_query for stickiness people
* Minor cleanup
* Add tests (and missing file) to group filtering in stickiness
* Allow aggregating by groups in stickiness
* Show group property filters in FE for stickiness
* convert the smallest of the funnel test files
* convert unorder funnel person test to journey for helper
* convert another file
* convert another file
* convert another file
* convert another file
* convert another file
* undelete snapshot files
* undelete snapshot files
* Revert "convert another file"
This reverts commit ef08511509.
* seperate clickhouse and postgres queries
* move to single query
* remove ununsed imports
* fix cohort + subquery issues
* some cleanup
* fix mypy issue
* fixes to query + tests
* add test for person and cohort properties
* remove cruft
* fix api tests
* Remove cohort + person prop filter from postgres
* move cohort and person property tests to clickhouse
* Filter down events
* typing fix
* fix test
* remove unneeded snapshot
* tests working with snapshots
* switch limit to property
* use materialized columns
* move to new distinct_id query
* add snapshots
* fix materialized column bug
* support cohort and person prop filters
* add person and cohort filtering
* remove cohort filtering from clickhouse
* small tweaks
* Lint fix
* remove cohort comment
* feat(funnels): update frontend to use new people_urls in response
This change updates the `FunnelBarGraph` and `FunnelStepTable`
components to use the new `converted_people_url` and
`dropped_poeple_url` in the funnels response.
I need to check that this covers all the cases for funnels. I've only
added people urls for funnels of type step for ordered/unordered/strict
and haven't yet touched the time bins and conversion time funnel
endpoint variants.
* add /some/people/url/ to tests
* chore: add action back, update tests to reference it
* fix typing
* wip
* get list of groups
* move backend endpoints
* frontend wip
* fix routes for groups
* add groups file
* try to fix tab nav
* fix groups query
* reformat results, add limits and offsets and next url
* move groups pages logic into own file
* fix and clean up tabs
* account for pagination and response reformatting
* lint fixes
* optional prev input
* typescript errors
* typescript fixes
* address feedback comments
* groups list logic test
* render properties expandable row
* fix test and lints
* prettier
* simplify table column title
* Fix a typing issue
* Use enum > boolean parameter
This makes what's going on more explicit
* Turn off pagination at the bottom of the table
* Rename table column
* Make pagination in groups work
Quite bugs fixed:
1. `previous` page was always shown, even if going into negative offsets
2. query_result could never be larger than `limit` with the code
* Cleanup code
* Make sidenav active under persons
* Use the correct query
* Add tests for pagination
* Update wording again
Co-authored-by: Karl-Aksel Puulmann <oxymaccy@gmail.com>
* cumulative dau for non breakdown
* breakdown case
* clean up test
* add trends request util
* use simpler test util
* types
* insight tests
* add snapshots
* black
* adds a first draft of a test helper for clearer event setup in tests
* one spelling of journeys
* obey the type checker
* convert all of breakdown_cases to the new test helper
* Removes unused helper method
* test(funnel-people): add tests for converted/dropped people urls
As per https://github.com/PostHog/posthog/issues/6935 we are adding urls
to responses to attempt to improve consistency between insight responses
and the people we display in the UI.
This simply adds tests for these urls, just for funnel step response
shape. The other two types of response will be handled separately.
* feat(funnel-people): return converted/dropped people url in funnel
Here I have simply added converted / dropped urls in the base funnel.
This touches both clickhouse and postgres functionality, so I will
probably add in tests for postgres also, or just disable to postgres.
It doesn't pass yet as there is an issue in that the order appears to be
ignored by the people endpoint.
* fix(funnels): actually use strict/unordered persons querying
Previously we were always using the standard `ClickhouseFunnelPersons`
class for retrieving people from the `/api/persons/funnel/` endpoint.
This change selects from the unordered and strict variants based on the
`funnel_order_type` setting.
Refers to https://github.com/PostHog/posthog/issues/7058 although there
is a frontend component to add that will truely resolve the issue.
* feat(funnel-people): add people urls for funnels with breakdown
In this I have also removed any changes from the non-clickhouse code.
Note that there are two places I've added the url generation code, one
in the `ClickhouseFunnelBase` and another in the `ClickhouseFunnel`
I think the former covers the unordered and strict cases, and the later
for the breakdown case. I think there are further test that I'll need to
add to validate e.g. if breakdown + strict work as expected.
* Fix people urls for unordered funnels + breakdown
* test: add test for strict breakdown with people urls
* make funnel response assertions not check people url equality
* fix typing
* fix tests
* remove new line in postgres funnel.py
* clear cache on insight test start
* no really, clear the cache
* remove flakiness from strict funnel test
* correct the unordered test
* use absolute uris
* use step.index not step.order
* remove out of date comment
* use step.index, not step.order
* use step.index, remove unordered funnels comment
* use journeys_for instead of create_events
* add test_helper_methods
* move all the tests where the properties are the same for all events to the journey helper
* compare funnel results without caring about person order
* spell words correcterly
* Revert "spell words correcterly"
This reverts commit befb83b183.
* Revert "compare funnel results without caring about person order"
This reverts commit 268927b8ba.
* correct types for test props
* add groups property values
* update groups property tests
* newline
* fix
* update test
* python black
* clean up tests
* rename to endpoint in operator value select
* add empty property values test
* do not return in an array
* fix
* feat(correlation): use people_url to load people modal
This change adds a new method to the `personsModelLogic` to allow for
specifying a url to be used to retrieve people from. I've avoided
overloading the existing `loadPeople` and rather added a new one,
`lostPeopleFromUrl`.
Currenlty this is only being used by correlations, but the intention is
to extend it's usage to anywhere else that is performing drilldowns to
people from, for instance, the trends aggregation.
* add paycard back
* make labels look right
* remove unused code
* fix typing in test
* fix typing in personsModelLogic
* refactor to make eventUsageLogic work
* fix typing
* fix typing again
* remove some funnel stories
* get storybook working with paycard
* cleaned up the interface a little
* chore(correlation): use `api.get` for fetching people
This updates to use api.get, and also converts the returned uri from the
correlation endpoint to an absolut uri, instead of just an absolute
path.
The `api.get` method expects either an abolute uri, or a relative path.
I'd rather not use an relative path as it's not obvious what it should
be relative to.
* fix tests
* make storybook uris absolute
* Paths filtering by groups backend
* update correlation tests, now that CTEs are included in sqls
* use decorator for materialising to ensure clean up happens
* cleanup offending tests
* feat(correlation): add people drill down urls for event correlation
This change simply adds urls in the response of the correlation endpoint
for each correlation returned. Note that this only adds support when
using correlation_type=events, as the
correlation_type=events_with_properties requires further changes that
I'd like the separate out to keep this PR small.
* feat(correlations): add people by property to correlation response
This commit covers the PROPERTIES case for making sure we return a url
that can be used to retrieve the people associated with a correlation,
either success or failure. This case is a completely different url than
for the events people endpoint as we are reusing the funnel people
endpoint, and filtering by "funnel_step_breakdown".
I'm uncertain if this is actually the correct url at this point in time,
as I have just attempted to copy what I have seen in the request from
the live running app.
* fix test
* Remove another param
* fix mypy typing
* Fix tests
* Add url response support for event_with_properties
* remove type assertion
* remove variable hack
* Remove funnel_steps
* use with_data and to_params
* Remove comment regarding complexity, it seems to pass the tests so...
* Add autocapture support for people url
* refactor people url construction a little
* remove properties attr for event people request
* fix if
* no really, fix if not None
* Remove _assert_never, mypy needs updating
* Fix no return mypy error
* Remove json.dumps
* add window-id to ingestion
* move window_id into snapshot data
* Add tests
* add window_id to snapshot_data only if included in the event
* add window_id to session_recording_events table
* revert ph-js downgrade
* fix data generator
* remove partition change
* update window_id defaults for tests
* missed one window_id default
* rename migration for conflict
* Migration to use materialized columns for groups
Workaround for https://github.com/PostHog/posthog/issues/6422
* Use groups materialized columns in queries
* Update mat column creation tests
* Simplify aggregation_target_field
* Fix migration
* Update snapshots
* smallest change to make aggregation work
* address comments
* add snapshot
* move function to groups model
* update funnel snapshot
* rename person_id to aggregation_target
* update snapshots as well
* dont support persons query mods for now
* update snapshot
* make array orders deterministic
* Improve process_math
* Add test for overlapping group keys
* Improve event query tests
* Add test for filtering by person properties together with groups
* Avoid flaky tests due to cohort_id changing
* Update queries and snapshots
* Add groups stuff
* Rename column from person_id to `target` in retention queries
No behavioral change, preparing for groups work :)
* Remove dead if statement
* WIP: Retention aggregation by groups
* Handle aggregation by groups in retention
Also handles the case where not every event has a property defined
* Test groups validation mixin
* Reformat
* Improve test for aggregation in retention
* Add /api/projects/@current/groups/property_definitions
To load property definitions for groups
* Add routes for fetching group types
* FE: Group analytics feature flag
* FE: Group analytics base types for properties
* FE: Initial implementation of fetching logics
* add group tabs to filter
* make sure group properties populate and refactor things
* prettier
* disable unused vars
* allow indexing objects by number
* mount group properties logic
Co-authored-by: Li Yi Yu <li@posthog.com>
* Extract GroupsJoinQuery
* Add test for breakdown filtering
* Unify breakdown mixins
* Allow passing breakdown_type == 'group' with breakdown_group_type_index
* Allow breakdown by group props in trends
* Add tests for trends breakdown_props function on group breakdowns
* Solve common issues
* Output snapshot diff into console
* Clean up materialized columns after tests
* Add zero protection
* Solve test failure
* Type math in Entity
* Allow passing group_type_index from FE to BE
* Get a initial query running
* Add group value filter if aggregating by groups
* Add snapshot testing for trends queries
* isort
* Update tests
* Add test for column_optimizer
* Update ee/clickhouse/queries/trends/util.py
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
* adds a test to prove that without any changes the API receives a string and returns one see #938
* put a guard in place so that funnel query can be shifted to arrays without affecting existing clients
* make checking for single property breakdowns safer
* sort imports
* sort imports
* reformat files
* Revert "reformat files"
This reverts commit 58530f134f191d53b927abe6fb6f5d2d384cb255.
* expand short variable names
* corrects a typo
* it wasn't a typo it was a logic error
* Add group type, group_type_index
* Raise an error when handling unsupported properties in CH
* Improve repr
* Fix is_superset function
This was previously broken - sorting and zipping doesn't really work for
this intent.
* Add group_type_index to analysis results
* Add `group_types_to_query`
* Minor typing fixes
* Create groups tables in tests
* Simple first filter by groups query
* isort
* Use snapshot testing in event_query tests, add test for groups
Co-authored-by: Marcus Hyett (PostHog) <85295485+marcushyett-ph@users.noreply.github.com>
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
* feat(correlation): add team wide person property exclusion list
This change just adds the exclusion list to the `Team` model and checks
that it can be updated. Separately we can:
1. add interface for the Project page to display
2. pull and update this list from the funnels correlation page
NOTE: We don't perform any validation on the structure, :fingerscrossed:
this won't be an issue. Alternative would be to use ArrayField, but use
of JSONField is consistent with other fields.
* test(correlation): add test checking exclude properties pulled from team
* feat(correlation): load exclude properties from team settings
Previously we were loading exclude properties from local storage, so we
would not be sharing the exclusion list between users. This change
simply plugs the `excludePropertyNames` into the `teamLogic` for the
purpose of persisting and loading the values.
* use [teamLogic.actionTypes.loadCurrentTeamSuccess]
* get tests passing
* switch frontend to using `correlation_config`
* refactor: use Team.correlation_config for persistence
* add project settings for correlation
* fix lint
* ensure excluded properties are saved to project config
* Add default excluded properties
* format
* make propertyCorrelations not null
* ensure excluded property names config is unique
* rename excludeProperty to excludePropertyFromProject
* update var names
* change to targetProperties
* remove null special casing
* update to filter client side on exclude from project clicked
* update test name to reflect new functionality
* fix tests
Without this, to run plugin-server tests you need to reset all
containers every time since otherwise both test- and non-test clickhouse
would attempt to read from the same topic.
* backend fixes and test
* add breakdown value to pie chart
* adjust test
* fix faulty test
* fill param
* fix formula tests
* more date passing
* more cleanup
* all tests working
* make test data explicit and add better checks
* support both ee and postgres
* length checks
* paginate recording compression
* some tests
* more accurate duration calculation
* add tests and types
* tons of decompression fixes
* rename test file to avoid conflict
* move decompression to helper
* add test for helper
* type fix
* rename method
* simplify paginated decomression
* handle case where offset exceeds length
* clean up
* test fixes
* clean up on aisle 12
* Add surrounding object for metadata response
* Add table for group_type_mapping
* Remove materialized columns from events table schema
These are not used and not needed w/ new mat columns work
* WIP: Migration to add group analytics columns
* Remove event table changes temporarily
* initial refactoring
* popup UI
* refactor path cleaning logic
* add nullable
* all ui working
* fix migration
* use regex replacement from team object
* add flag
* add switch
* fix type
* fix type
* UI update
* restore removed arg
* add local path cleaning filters to api
* add test for local path filters
* working new UI
* reduced repeated code
* fix numbering
* minor refactoring
* update copy
* add under advanced features
* address comments, minor cleanup
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
Previously we would attempt to generate a response even though there
were no steps. There appears to be some code paths that blow up if this
happens, so instead we return as soon as we can in this case. This
appears to be the behaviour elsewhere also.
This resolves the sentry error found here:
https://sentry.io/organizations/posthog/issues/2718768248/
* paginate session recording events api
* code quality
* don't rerender replayer every time events get loaded
* refactor session recordings, make it backwards compatible, add bunch of tests
* move limit and offset to after decompress
* change limit
* add caching of recording
* add duration
* fix a few tests
* fix api tests
* add partial chunk test
* fix default limit test
* code quality
* typing
* fix backend tests
* mypy fixes and signature
* remove circular dependency
* mypy and sessionsplaylogic tests
* fix migration
* make single migration
* revert mypy typing
* remove require react resolve
* fix loading state to persist across multi chunks and add test'
* cleanup
* duration to ms
* fix duration tests
* remove require react resolve
* fix test
* bump rrweb player
* change cache behavior plus more
* fix frontend tests and make duration calculation more robust
* fix timestamp in ms bug in tests
* fix duration 0 test
* fix compatibility with rrweb-player
* update lockfile
* yarn unlink
* resolve kea-test-utils changes
* another one
* remove caching for now (leave as todo) and change limit to 100
* Refactor column_optimizer to work differently
* WIP: Use counter over set
* Handle person filters in person query
* Remove a dead argument
* Use enum over parameter for determining behavior
* Allow excluding person properties mode when handled in person query
* Fix _get_person_query type
* Use correct table for funnel_event_query
* Remove unneeded override
* Add extra typing
* Filter by entity.properties in person query for trends
* Handle error 184 due to naming clash
* Better default for prop_filter_json_extract
* Update column_optimizer tests for Counter
* Handle person_props as extra_fields
* Handle breakdowns and person property filter pushdown
* Transform values correctly
* Simplify get_entity_filtering_params
* Fix funnel correlations
* Solve caching issues in trend people queries
* Remove @skip test
* Add syrupy tests for parse_prop_clauses
Can update these via --snapshot-update
* Add snapshot tests for person queries
* Add a few notes
* Update test to avoid collision
* Kill dead code
* Handle PR comments
* Update ee/clickhouse/queries/person_query.py
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
* Add `slug` fields to `Organization` and `Team`
* Expose slugs to user
* Add slug autogeneration for new orgs/projects
* Improve slug UX
* Remove slug from settings
* Update org/team instance creation plus add tests
* Only require project slug to be unique for org, not globally
* Fix `get_prep_value`
* Test organization slugification
* Deslugify `Team`
* Clean up changes
* Update test_user.py
* Apply suggestions from code review
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
* Random 4 letter suffixes for the win
* Fix import
* Ignore `test_migrations_are_null`
* Fix `RunSQL` query being empty
* Fix `generate_random_short_suffix` testing
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
This seems to be semi-consistently failing locally for me and
inconsistently on CI. The cause is unknown - debugging locally, this
seems more of a query correctness issue than a test data incomplete
issue.
* fix bug where session recording is split by new distinct_id
* fix query bug to allow distinct_id clause
* Basic query filtering by events on clickhouse
* add duration filtering
* Add multiple action/event filters
* Move to using person_id + optimize query
* add postgres support and querying on person_id
* move back to distinct_ids
* remove lots of duplicated logic
* Add pagination to backend
* Pagination
* Add duration and date filter
* Use person header is list view
* type fixes
* bug fix
* bugs and tests
* test fixes
* style filters
* logic tests
* Add another test for team leakage
* fix flaky test
* UX changes
* UX tweaks
* auto focus filter box on open
* add test for recording viewed change
* move duration filter to using a tested logic
* move to clsx
* add debounce breakpoint
* Small style change
* fix debounce
* fix breakpoint
* move test to defaultAPIMocks (merging changes)
* react to url change
We'll be using qemu that ships with docker for mac. I'd updated this at
the same time as zookeeper but obviously never removed the kafka
container from before somehow.
* WIP: Create new property types for simplified cohorts
* Add documentation on simplified_cohort_filter_properties
* Handle static-cohort/precalculated-cohort property types
* Handle new property filters properly
* Add casting
* Test cohorts in more cases
* Fix a bug
* Fix benchmark simplifying
* Avoid redoing work every setup for benchmarks
* Update typing;
* Remove unneeded scope
* Add tests for simplifying and cohorts
* Roll more of "do we need to join persons table" behavior into ClickhousePersonQuery class
* Handle precalculated cohort logic in sessions
* Simplify event query
* More tests without any JSONExtract
* Simplify entity properties as well
* Improve docstring
* Add test for breakdown & precalculated cohorts
* Add test for filtering sessions by precalculated cohorts
* Reset unneeded change
* Update cohort
* Solve some typing issues
* Update benchmarking
* Fix cohort filtering tests
* Fix cohort tests
* Fix a caching issue
* Typecheck
* Handle exclusion filters
* Simplify filters code
* Simplify filters ASAP if filter is created
* Simplify route
* Remove simplification-specific logic from queries
* Remove recursion, update tests
* Pass team in more cases
* Update column optimizer specs
* Test simplify
* Update trends test
* Fix rebase fail
* events dead letter queue CH table
* format
* update schemas
* also store raw payload
* better naming
* make table name more clear
* wip better testing
* remove unused imports
* remove kafka test
* prevent non null test from running on CH migrations
* add kafka testing
* minor tests cleanup
* test naive longer sleep
* make test end-to-end
* address review
* update ttl, format
* refactor delay func, address review
I've been getting lot's of errors with the qemu emulated x86 version.
I'm just changing the arm docker-compose as I don't want my issues with
local dev to affect others.
* fix(correlation): ensure correlation partitioned by team
Previously if distinct_id's were the same between two teams, we'd end up
pulling in the event data between the teams.
* dev(tests): clear cache between partition calls
* fix(correlation): add lower bounds for selected events
Previously we would consider all events for correlation calculation. Now
we use the funnel `date_from` as the lower bounds.
* chore(correlation): exclude funnel steps
* chore(correlation): make sure cache is cleared before each test
* Update funnel success comment
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
* fix: filter events by team_id
* chore(correlation): remove CTEs from correlation query
There seems to be an issue with the CTEs and production clickhouse, see
https://github.com/ClickHouse/ClickHouse/issues/29748
Instead of risking it, I'm just removing them.
* chore: update entities -> events for funnel step exclusion
* fix team_id = team_id issue
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
* chore(diagnose): add a stub endpoint for event diagnosis
This adds an insight endpoint that takes a `target_entity` and returns
a list of events ordered by significance of a person reaching
`target_entity`
Followup PRs will add actual calculations but this should act as a
conversation piece around the structure of request and response, as well
as a stub from which UI development can start.
* play around to get mypy typings right
* Sort out test reponse structurea
* refactor: address CR comments
* feat(diagnose): add diagnose stubs for implementation
* feat(funnel): add event correlation calculation implementation
This adds to the `/api/projects/<team_id>/funnel/correlation` endpoint
an implementation that calculates the odds_ratios for each event that a
user that has been part of a funnel, successful or otherwise.
* chore(correlation): get query working
* refactor(correlation): move functions to Query methods
* Always allow filtering on distinct id
* fix
* fix
* remove accidentally commited test
* include table name
* add table specific because distinct_id doesn't exist on person table
Co-authored-by: eric <eeoneric@gmail.com>
* make sure funnel and path dates are always aligned and add api handling for funnel filter persons
* use post instead of GET for paths
* parse label
* change type
* use post in test
* fix types
* test both get and post
Our queries now contain a lot of comment noise that's not relevant when
developing. This change makes PRINT_SQL env variable usable again by
stripping these comments.
* dev(clickhouse): strip out comments before executing sql
This is so we can easily copy/paste from e.g. Metabase by querying the
system.query_log. In metabase is doesn't display new lines (although you
can download to file for this), but it's not very practical.
* test(clickhouse): use `capture_select_queries` in comment strip test
* test(clickhouse): only sub. params if non-insert query
This parallels `clickhouse_driver` behaviour.
* chore(clickhouse): move sql preparation to dedicated function
* refactor: rearrange func and type definitions
* Add asv code
* Get a benchmark running
* better output folder
* Move benchmark file
* Cleanup of config
* Run a query and benchmark
* Skip benchmarks for isort
* Set up materialized columns before test
* Better skipping logic
* Add first proper benchmark, add some documentation
* Person property filtering
* Add new workflow
* Show stderr in test run
* Continue debugging actions
* Try to save benchmark results to separate repo
* Output to main directory
* Scheduling
* Remove if temporarily
* Int for ms
* Comment on the PR
* Collapsible section
* Update README
* Clarification
* Remove h3
* Remove pyproject.toml, .gitignore changes that are unneeded
* Add project-nested version of all project-dependent endpoints
* Fix hook `perform_create`
* Adjust `plugin-configs` to adhere to style of other endpoints
* Test Kafka
* black format python
* fix imports
* add kafka and zk deps for testing
* Include ZK and Kafka for all tests
* fix signature for kafka helper
* Connect to localhost for kafka
* update kafka host for all test runs
* Wrong env var for kafka
* consolidate env vars for github actions
* set the advertised hostname from the broker to localhost
* add env var to docker-compose for kafka broker advert host
* resort to what we do locally with /etc/hosts
* Remove configs for kafka that won't be used
* restore progress
* working connection no UI visual
* working for events
* edit endpoint to start point
* working with close button
* funnel to path work (no dropoff yet)
* run prettier
* make suggested adjustmenst
* Refactor `AvailableFeature` from strings to an enum everywhere
* Fix circular dependency and type
* Add "Per-project access" feature flag, premium feature, and organization switch
* Rename `OrganizationMembershipLevel` to `OrganizationAccessLevel`
* Create `ExplicitTeamMembership` model
* Show whether projects are restricted in the project switcher
* Update organizations API code
* Fix migrations
* Move organization tests that require EE to `ee`
* Revert `OrganizationMembershipLevel` rename
* Fix organization tests
* Update migration
* Fix schema and add Members to Project Settings
* Build out test memberships API with security tests
* Update `TeamMembers` and `teamMembersLogic`
* Move "Per-project access" description to tooltip
* Add moar tests
* Fix Project Members list logic
* Add additional membership checks
* Update migrations
* Fix typing
* Adjust explicit team memberships API similarly
* Fix typo
* Unify `ExplicitTeamMemberSerializer`
* Remove old changes to `membersLogic` usage
* Use `effective_membership_level` on `TeamBasicSerializer`
* Clean up organization update tests
* Explicitly disallow enabling per-project access for free
* Fix circular import
* Remove `id` from `UserSerializer`
* Fix typing
* Try to fix import
* Fix fatal typing
* Add more tests
* Update permissioning.ts
* Add clarifying comment to migration
* Fix import
* Revert `TopNavigation` changes
* Restore `TopNavigation` changes
This reverts commit 05fd9e4ed6.
* Try to add a story for `TopNavigation`
* minor clarifications
* Revert `TopNavigation` changes
* Restore `TopNavigation` changes
* Make new access control entirely project-based
* Update migrations
* Add `project_based_permissioning` to `TeamBasicSerializer`
* Update test_team.py
* Fix `isRestricted` in `ProjectRow`
* Disable project creation for non-admins
* Make project icon in top nav itself dynamic as well
* Fix story
* Delete 0169_project_based_permissioning.py
* Apply suggestions from code review
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
* Update frontend/src/layout/navigation/TopNavigation.tsx
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
* Address feedback
* Project-based permissioning full data access restrictions (#6068)
* Fix Access Control restriction tooltip
* Add `TeamMemberAccessPermission` and use it in viewsets
* Add `ErrorProjectUnavailable` scene
* Ignore mypy
* Update MainNavigation.tsx
* Update explicit_team_member.py
* Fix frontend detection of unavailable project
* Fix some tests and edge cases
* Fix basic permissions
* Add more tests
* Simplify `ExplicitTeamMemberViewSet` permissions
* Improve restrictions and add moar tests
* Update frontend
* Fix a couple of things
* Fix import
* Fix some edge cases
* Fix typing errors
* Use hedgehog instead of moth
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
* Address feedback
* Add proper permissioning to dashboard views
* Update ee/api/test/test_dashboard.py
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
* Run prettier
* Remove debug code
Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>